summaryrefslogtreecommitdiffstats
path: root/docs
diff options
context:
space:
mode:
Diffstat (limited to 'docs')
-rw-r--r--docs/html-intl/intl/es/about/versions/android-5.0.jd635
-rw-r--r--docs/html-intl/intl/es/about/versions/lollipop.jd249
-rw-r--r--docs/html-intl/intl/ja/about/versions/android-5.0.jd635
-rw-r--r--docs/html-intl/intl/ja/about/versions/lollipop.jd256
-rw-r--r--docs/html-intl/intl/ko/about/versions/android-5.0.jd636
-rw-r--r--docs/html-intl/intl/ko/about/versions/lollipop.jd246
-rw-r--r--docs/html-intl/intl/pt-br/about/versions/android-5.0.jd633
-rw-r--r--docs/html-intl/intl/pt-br/about/versions/lollipop.jd256
-rw-r--r--docs/html-intl/intl/ru/about/versions/android-5.0.jd636
-rw-r--r--docs/html-intl/intl/ru/about/versions/lollipop.jd251
-rw-r--r--docs/html-intl/intl/zh-cn/about/versions/android-5.0.jd14
-rw-r--r--docs/html-intl/intl/zh-tw/about/versions/android-5.0.jd635
-rw-r--r--docs/html-intl/intl/zh-tw/about/versions/lollipop.jd254
-rw-r--r--docs/html/about/about_toc.cs21
-rw-r--r--docs/html/about/dashboards/index.jd53
-rw-r--r--docs/html/about/versions/android-5.0-changes.jd21
-rw-r--r--docs/html/design/style/iconography.jd28
-rw-r--r--docs/html/design/wear/watchfaces.jd39
-rw-r--r--docs/html/distribute/tools/promote/device-art-resources/wear/thumb.pngbin0 -> 5214 bytes
-rw-r--r--docs/html/distribute/tools/promote/device-art-resources/wear_round/port_back.pngbin0 -> 40294 bytes
-rw-r--r--docs/html/distribute/tools/promote/device-art-resources/wear_square/port_back.pngbin0 -> 25381 bytes
-rw-r--r--docs/html/distribute/tools/promote/device-art.jd138
-rw-r--r--docs/html/google/gcm/adv.jd410
-rw-r--r--docs/html/google/gcm/c2dm.jd12
-rw-r--r--docs/html/google/gcm/ccs.jd58
-rw-r--r--docs/html/google/gcm/client.jd146
-rw-r--r--docs/html/google/gcm/gcm.jd339
-rw-r--r--docs/html/google/gcm/gs.jd17
-rw-r--r--docs/html/google/gcm/http.jd129
-rw-r--r--docs/html/google/gcm/notifications.jd6
-rw-r--r--docs/html/google/gcm/server-ref.jd763
-rw-r--r--docs/html/google/gcm/server.jd648
-rw-r--r--docs/html/google/google_toc.cs13
-rw-r--r--docs/html/google/play-services/ads.jd6
-rw-r--r--docs/html/google/play/billing/billing_integrate.jd12
-rw-r--r--docs/html/google/play/billing/billing_reference.jd7
-rw-r--r--docs/html/guide/practices/screens_support.jd50
-rw-r--r--docs/html/guide/topics/data/backup.jd9
-rw-r--r--docs/html/guide/topics/media/exoplayer.jd56
-rw-r--r--docs/html/guide/topics/resources/available-resources.jd1
-rw-r--r--docs/html/guide/topics/resources/providing-resources.jd18
-rw-r--r--docs/html/guide/topics/ui/notifiers/notifications.jd19
-rw-r--r--docs/html/images/exoplayer/adaptive-streaming.pngbin40791 -> 40489 bytes
-rw-r--r--docs/html/images/opengl/ogl-triangle-projected.pngbin11624 -> 7454 bytes
-rw-r--r--docs/html/images/opengl/ogl-triangle-touch.pngbin12839 -> 9688 bytes
-rw-r--r--docs/html/images/opengl/ogl-triangle.pngbin11182 -> 7123 bytes
-rw-r--r--docs/html/images/tools/projectview-p1.pngbin0 -> 30780 bytes
-rw-r--r--docs/html/images/tools/projectview-p2.pngbin0 -> 33649 bytes
-rw-r--r--docs/html/images/tools/studio-mipmap-folders.pngbin0 -> 8430 bytes
-rw-r--r--docs/html/images/tools/studio-project-layout.pngbin47374 -> 18344 bytes
-rw-r--r--docs/html/images/transitions/transition_sample_video.mp4bin0 -> 823950 bytes
-rw-r--r--docs/html/images/transitions/transition_sample_video.ogvbin0 -> 210884 bytes
-rw-r--r--docs/html/images/transitions/transition_sample_video.webmbin0 -> 215774 bytes
-rw-r--r--docs/html/images/transitions/transitions_diagram.pngbin0 -> 39338 bytes
-rw-r--r--docs/html/images/tv/app-browse.pngbin0 -> 226591 bytes
-rw-r--r--docs/html/images/tv/card-view.pngbin0 -> 307220 bytes
-rw-r--r--docs/html/images/tv/deep-link.pngbin0 -> 212656 bytes
-rw-r--r--docs/html/sdk/index.jd4
-rw-r--r--docs/html/sdk/installing/create-project.jd41
-rw-r--r--docs/html/tools/building/plugin-for-gradle.jd2
-rw-r--r--docs/html/tools/devices/emulator.jd2
-rw-r--r--docs/html/tools/projects/index.jd59
-rw-r--r--docs/html/tools/revisions/gradle-plugin.jd153
-rw-r--r--docs/html/tools/revisions/studio.jd29
-rw-r--r--docs/html/tools/studio/index.jd164
-rw-r--r--docs/html/tools/support-library/features.jd32
-rw-r--r--docs/html/tools/tools_toc.cs3
-rw-r--r--docs/html/training/articles/security-tips.jd12
-rw-r--r--docs/html/training/basics/fragments/support-lib.jd83
-rw-r--r--docs/html/training/basics/intents/sending.jd3
-rw-r--r--docs/html/training/graphics/opengl/draw.jd96
-rw-r--r--docs/html/training/graphics/opengl/environment.jd26
-rw-r--r--docs/html/training/graphics/opengl/motion.jd7
-rw-r--r--docs/html/training/graphics/opengl/projection.jd48
-rw-r--r--docs/html/training/graphics/opengl/touch.jd18
-rw-r--r--docs/html/training/location/display-address.jd680
-rw-r--r--docs/html/training/material/drawables.jd2
-rw-r--r--docs/html/training/multiscreen/screendensities.jd23
-rw-r--r--docs/html/training/training_toc.cs35
-rw-r--r--docs/html/training/transitions/custom-transitions.jd189
-rw-r--r--docs/html/training/transitions/index.jd80
-rw-r--r--docs/html/training/transitions/overview.jd165
-rw-r--r--docs/html/training/transitions/scenes.jd211
-rw-r--r--docs/html/training/transitions/transitions.jd315
-rw-r--r--docs/html/training/tv/discovery/index.jd5
-rw-r--r--docs/html/training/tv/discovery/recommendations.jd43
-rw-r--r--docs/html/training/tv/discovery/searchable.jd20
-rw-r--r--docs/html/training/tv/playback/card.jd156
-rw-r--r--docs/html/training/tv/playback/index.jd3
-rw-r--r--docs/html/training/tv/start/layouts.jd4
-rw-r--r--docs/html/training/wearables/data-layer/data-items.jd128
-rw-r--r--docs/html/training/wearables/data-layer/events.jd3
-rw-r--r--docs/html/training/wearables/data-layer/messages.jd22
-rw-r--r--docs/html/training/wearables/watch-faces/configuration.jd19
-rw-r--r--docs/html/training/wearables/watch-faces/drawing.jd51
-rw-r--r--docs/html/training/wearables/watch-faces/index.jd8
-rw-r--r--docs/html/training/wearables/watch-faces/service.jd33
97 files changed, 9497 insertions, 1835 deletions
diff --git a/docs/html-intl/intl/es/about/versions/android-5.0.jd b/docs/html-intl/intl/es/about/versions/android-5.0.jd
new file mode 100644
index 0000000..c94a140
--- /dev/null
+++ b/docs/html-intl/intl/es/about/versions/android-5.0.jd
@@ -0,0 +1,635 @@
+page.title=API de Android 5.0
+excludeFromSuggestions=true
+sdk.platform.version=5.0
+sdk.platform.apiLevel=21
+@jd:body
+
+
+<div id="qv-wrapper">
+<div id="qv">
+
+<h2>En este documento <a href="#" onclick="hideNestedItems('#toc44',this);return false;" class="header-toggle"> <span class="more">mostrar más</span> <span class="less" style="display:none">mostrar menos</span></a></h2>
+
+<ol id="toc44" class="hide-nested">
+ <li><a href="#ApiLevel">Actualiza el nivel de la API de destino</a></li>
+ <li><a href="#Behaviors">Cambios importantes de comportamiento</a>
+ <ol>
+ <li><a href="#ART">Si no probaste la aplicación con el nuevo Android Runtime (ART)…</a></li>
+ <li><a href="#BehaviorNotifications">Si la aplicación implementa notificaciones…</a></li>
+ <li><a href="#BehaviorMediaControl">Si la aplicación usa RemoteControlClient…</a></li>
+<li><a href="#BehaviorGetRecentTasks">Si la aplicación usa getRecentTasks()…</a></li>
+<li><a href="#64BitSupport">Si usas el kit de desarrollo nativo (NDK) de Android…</a></li>
+<li><a href="#BindService">Si la aplicación se vincula a un servicio…</a></li>
+<li><a href="#BehaviorWebView">Si la aplicación usa WebView…</a></li>
+ </ol>
+ </li>
+ <li><a href="#UI">Interfaz de usuario</a>
+ <ol>
+ <li><a href="#MaterialDesign">Compatibilidad con diseño de materiales</a></li>
+ <li><a href="#Recents">Documentos y actividades concurrentes en la pantalla de actividades y tareas recientes</a></li>
+ <li><a href="#WebView">Actualizaciones de WebView</a></li>
+ <li><a href="#ScreenCapture">Captura y uso compartido de pantalla</a></li>
+ </ol>
+ </li>
+ <li><a href="#Notifications">Notificaciones</a>
+ <ol>
+ <li><a href="#LockscreenNotifications">Notificaciones de pantalla bloqueada</a></li>
+ <li><a href="#NotificationsMetadata">Metadatos de notificaciones</a></li>
+ </ol>
+ </li>
+ <li><a href="#Graphics">Gráficos</a>
+ <ol>
+ <li><a href="#OpenGLES-3-1">Compatibilidad con OpenGL ES 3.1</a></li>
+ <li><a href="#AndroidExtensionPack">Android Extension Pack</a></li>
+ </ol>
+ </li>
+ <li><a href="#Media">Medios</a>
+ <ol>
+ <li><a href="#Camera-v2">API de cámara para capacidades avanzadas de la cámara</a></li>
+ <li><a href="#AudioPlayback">Reproducción de audio</a></li>
+ <li><a href="#MediaPlaybackControl">Control de reproducción de medios</a></li>
+ <li><a href="#MediaBrowsing">Exploración de medios</a></li>
+ </ol>
+ </li>
+ <li><a href="#Storage">Almacenamiento</a>
+ <ol>
+ <li><a href="#DirectorySelection">Selección de directorio</a></li>
+ </ol>
+ </li>
+ <li><a href="#Wireless">Redes inalámbricas y conectividad</a>
+ <ol>
+ <li><a href="#Multinetwork">Múltiples conexiones de red</a></li>
+ <li><a href="#BluetoothBroadcasting">Emisión de Bluetooth</a></li>
+ <li><a href="#NFCEnhancements">Mejoras de NFC</a></li>
+ </ol>
+ </li>
+ <li><a href="#Power">Proyecto Volta</a>
+ <ol>
+ <li><a href="#JobScheduler">Programación de trabajos</a></li>
+ <li><a href="#PowerMeasurementTools">Herramientas de programadores para el uso de la batería</a>
+ </ol>
+ </li>
+ <li><a href="#Enterprise">Android en el entorno de trabajo y en el entorno educativo</a>
+ <ol>
+ <li><a href="#ManagedProvisioning">Aprovisionamiento administrado</a></li>
+ <li><a href="#DeviceOwner">Propietario de dispositivo</a></li>
+ <li><a href="#ScreenPinning">Fijación de pantalla</a></li>
+ </ol>
+ </li>
+ <li><a href="#System">Sistema</a>
+ <ol>
+ <li><a href="#AppUsageStatistics">Estadísticas de uso de aplicaciones</a></li>
+ </ol>
+ </li>
+ <li><a href="#Printing">Marco de impresión</a>
+ <ol>
+ <li><a href="#PDFRender">Representación de PDF como mapa de bits</a></li>
+ </ol>
+ </li>
+ <li><a href="#TestingA11y">Pruebas y accesibilidad</a>
+ <ol>
+ <li><a href="#TestingA11yImprovements">Mejoras de pruebas y accesibilidad</a></li>
+ </ol>
+ </li>
+ <li><a href="#IME">IME</a>
+ <ol>
+ <li><a href="#Switching">Cambio más sencillo de idiomas de entrada</a></li>
+ </ol>
+ </li>
+ <li><a href="#Manifest">Declaraciones de manifiesto</a>
+ <ol>
+ <li><a href="#ManifestFeatures">Características requeridas declarables</a></li>
+ <li><a href="#Permissions">Permisos de usuario</a></li>
+ </ol>
+ </li>
+</ol>
+
+<h2>API Differences</h2>
+<ol>
+<li><a href="{@docRoot}sdk/api_diff/21/changes.html">API level 20 to 21 &raquo;</a> </li>
+<li><a href="{@docRoot}sdk/api_diff/preview-21/changes.html">L Developer Preview to 21 &raquo;</a> </li>
+</ol>
+
+<h2>See Also</h2>
+<ol>
+<li><a href="{@docRoot}about/versions/android-5.0-changes.html">Android 5.0 Behavior Changes</a> </li>
+<li><a href="{@docRoot}about/versions/lollipop.html">Android Lollipop Highlights</a> </li>
+</ol>
+
+</div>
+</div>
+
+<p>Nivel de API: {@sdkPlatformApiLevel}</p>
+
+<p>Android 5.0 (<a href="{@docRoot}reference/android/os/Build.VERSION_CODES.html#LOLLIPOP">LOLLIPOP</a>) ofrece nuevas funciones para los usuarios y los programadores de aplicaciones. En este documento, se proporciona una introducción a las API nuevas más destacadas.</p>
+
+<p>Para conocer con más detalle las nuevas funciones de la plataforma, consulta los <a href="{@docRoot}about/versions/lollipop.html">Aspectos destacados de Android Lollipop</a>.</p>
+
+
+<h3 id="Start">Empieza a programar</h3>
+
+<p>Si deseas empezar a crear aplicaciones para Android 5.0, primero debes <a href="{@docRoot}sdk/index.html">obtener el SDK de Android</a>. Luego, usa el <a href="{@docRoot}tools/help/sdk-manager.html">Administrador de SDK</a> para descargar las imágenes del sistema y la plataforma de SDK de Android 5.0.</p>
+
+<h3 id="ApiLevel">Actualiza el nivel de la API de destino</h3>
+
+<p>Si deseas optimizar de una mejor manera la aplicación para dispositivos que tienen Android {@sdkPlatformVersion}, establece <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> en <code>"{@sdkPlatformApiLevel}"</code>, instala la aplicación en una imagen del sistema de Android {@sdkPlatformVersion}, pruébala y luego publica la aplicación actualizada con este cambio.</p>
+
+<p>Puedes usar API de Android {@sdkPlatformVersion}, además de admitir versiones anteriores, agregando condiciones al código que comprueban el nivel de la API del sistema antes de ejecutar API no admitidas por <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a>. Para obtener más información sobre el mantenimiento de la compatibilidad con versiones anteriores, consulta <a href="{@docRoot}training/basics/supporting-devices/platforms.html">Compatibilidad con versiones de plataforma diferentes</a>.</p>
+
+<p>Para obtener más información sobre el funcionamiento de los niveles de API, consulta <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">¿Qué es un nivel de API?</a></p>
+
+<h2 id="Behaviors">Cambios importantes de comportamiento</h2>
+
+<p>Si publicaste previamente una aplicación para Android, ten en cuenta que la aplicación podría verse afectada por los cambios en Android 5.0.</p>
+
+<h3 id="ART">Si no probaste la aplicación con el nuevo Android Runtime (ART)…</h3>
+
+<p>La versión 4.4 introdujo un nuevo tiempo de ejecución experimental de Android, ART. En la versión 4.4, ART era opcional, y el tiempo de ejecución predeterminado seguía siendo Dalvik. Con Android 5.0, ART ahora es el tiempo de ejecución predeterminado.</p>
+
+<p>Para obtener una descripción general de las nuevas funciones de ART, consulta <a href="https://source.android.com/devices/tech/dalvik/art.html">Introducción a ART</a>. Algunas de las principales funciones nuevas son las siguientes:</p>
+
+<ul>
+ <li>compilación por adelantado (AOT);</li>
+ <li>recolección de basura (GC) mejorada;</li>
+ <li>compatibilidad con depuración mejorada.</li>
+</ul>
+
+<p>La mayoría de las aplicaciones de Android deberían funcionar sin ningún tipo de cambio en ART. Sin embargo, algunas de las técnicas que funcionan en Dalvik no funcionan en ART. Para obtener información sobre los problemas más significativos, consulta <a href="{@docRoot}guide/practices/verifying-apps-art.html">Verificación de comportamiento de aplicaciones en Android Runtime (ART)</a>. Presta especial atención en los siguientes casos:</p>
+
+<ul>
+ <li>La aplicación usa Java Native Interface (JNI) para ejecutar el código C/C++.</li>
+ <li>Usas herramientas de programación que generan código no estándar (por ejemplo, algunos ofuscadores).</li>
+ <li>Usas técnicas que son incompatibles con la compactación de la recolección de basura. ART no implementa actualmente la compactación GC, pero esta función está en programación en el proyecto de código abierto de Android.</li>
+</ul>
+
+<h3 id="BehaviorNotifications">Si la aplicación implementa notificaciones…</h3>
+
+<p>Asegúrate de que las notificaciones tengan en cuenta estos cambios de Android 5.0. Para obtener más información sobre el diseño de las notificaciones para Android 5.0 o versiones posteriores, consulta la <a href="{@docRoot}design/patterns/notifications.html">guía de diseño de notificaciones</a>.
+</p>
+
+<h4 id="NotificationsMaterialDesignStyle">Estilo de diseño de materiales</h4>
+<p>Las notificaciones se crean con texto oscuro sobre fondo blanco (o muy claro) para que coincidan con los nuevos widgets de diseño de materiales. Asegúrate de que todas las notificaciones se vean bien con el nuevo esquema de colores. Si las notificaciones se ven mal, corrígelas:</p>
+
+<ul>
+ <li>Usa {@link android.app.Notification.Builder#setColor(int) setColor()} para establecer un color de énfasis en un círculo detrás de la imagen del ícono. </li>
+ <li>Actualiza o elimina recursos que involucran color. El sistema ignora todos los canales no alfa en los íconos de acción y en el ícono de notificación principal. Debes asumir que estos íconos solo serán alfa. El sistema dibuja íconos de notificación en blanco e íconos de acción en gris oscuro.</li>
+</ul>
+
+<h4 id="NotificationsSoundVibration">Sonido y vibración</h4>
+<p>Si actualmente estás agregando sonidos y vibraciones a las notificaciones mediante el uso de las clases {@link android.media.Ringtone}, {@link android.media.MediaPlayer} o {@link android.os.Vibrator}, elimina este código para que el sistema pueda presentar notificaciones de forma correcta en modo de <em>prioridad</em>. En su lugar, usa los métodos {@link android.app.Notification.Builder} para agregar sonidos y vibraciones.</p>
+
+<p>Configurar el dispositivo en {@link android.media.AudioManager#RINGER_MODE_SILENT RINGER_MODE_SILENT} hace que el dispositivo pase al nuevo modo de prioridad. El dispositivo sale del modo de prioridad si lo estableces en {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_NORMAL} o {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_VIBRATE}.</p>
+
+<p>Anteriormente, Android usaba {@link android.media.AudioManager#STREAM_MUSIC STREAM_MUSIC} como la secuencia maestra para controlar el volumen de las tablets. En Android 5.0, la secuencia maestra de volumen tanto para teléfonos como para tablets ahora está unificada y controlada por {@link android.media.AudioManager#STREAM_RING STREAM_RING} o {@link android.media.AudioManager#STREAM_NOTIFICATION STREAM_NOTIFICATION}.</p>
+
+<h4 id="NotificationsLockscreenVisibility">Visibilidad de la pantalla bloqueada</h4>
+<p>De forma predeterminada, las notificaciones ahora aparecen en la pantalla bloqueada del usuario en Android 5.0. Los usuarios pueden elegir proteger la información confidencial de dicha exposición, en cuyo caso el sistema redacta automáticamente el texto que aparece en la notificación. Para personalizar esta notificación redactada, usa {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()}.</p>
+<p>Si la notificación no contiene información personal o si deseas permitir el control de la reproducción de medios en la notificación, llama al método {@link android.app.Notification.Builder#setVisibility(int) setVisibility()} y establece el nivel de visibilidad de la notificación en {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}.
+</p>
+
+<h4 id="NotificationsMediaPlayback">Reproducción de los medios</h4>
+<p>Si implementas notificaciones que presentan controles de transporte o estado de reproducción de medios, considera el uso de la nueva plantilla {@link android.app.Notification.MediaStyle}, en lugar de un objeto {@link android.widget.RemoteViews.RemoteView} personalizado. Cualquiera sea el enfoque que elijas, asegúrate de establecer la visibilidad de la notificación en {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC} a fin de que los controles estén accesibles desde la pantalla bloqueada. Ten en cuenta que, a partir de Android 5.0, el sistema ya no muestra objetos {@link android.media.RemoteControlClient} en la pantalla bloqueada. Para obtener más información, consulta <a href="#BehaviorMediaControl">Si la aplicación usa RemoteControlClient</a>.</p>
+
+<h4 id="NotificationsHeadsup">Notificación de aviso</h4>
+<p>Las notificaciones ahora pueden aparecer en una pequeña ventana flotante (también denominada notificación de aviso) cuando el dispositivo está activo (es decir, el dispositivo está desbloqueado y su pantalla está encendida). Estas notificaciones son similares a la forma compacta de tu notificación, salvo que la notificación de aviso también muestra los botones de acción. Los usuarios pueden actuar sobre una notificación de aviso o descartarla sin salir de la aplicación actual.</p>
+
+<p>Algunos ejemplos de condiciones que pueden desencadenar notificaciones de aviso incluyen:</p>
+
+<ul>
+ <li>La actividad del usuario está en modo de pantalla completa (la aplicación usa {@link android.app.Notification#fullScreenIntent}).</li>
+ <li>La notificación tiene alta prioridad y utiliza tonos o vibraciones.</li>
+</ul>
+
+<p>Si la aplicación implementa notificaciones en cualquiera de esos escenarios, asegúrate de que las notificaciones de aviso se presenten correctamente.</p>
+
+<h3 id="BehaviorMediaControl">Si la aplicación usa RemoteControlClient…</h3>
+<p>La clase {@link android.media.RemoteControlClient} ahora está obsoleta. Cambia a la nueva API {@link android.media.session.MediaSession} tan pronto como sea posible.</p>
+
+<p>Las pantallas bloqueadas en Android 5.0 no muestran controles de transporte para {@link android.media.session.MediaSession} ni {@link android.media.RemoteControlClient}. En cambio, la aplicación puede proporcionar un control de la reproducción de los medios desde la pantalla bloqueada a través de una notificación. De este modo, la aplicación tiene un mayor control sobre la presentación de los botones de medios, al mismo tiempo que proporciona una experiencia uniforme para los usuarios a través de los dispositivos bloqueados y desbloqueados.</p>
+
+<p>Android 5.0 introduce una nueva plantilla {@link android.app.Notification.MediaStyle} para este fin. {@link android.app.Notification.MediaStyle} convierte acciones de notificación que agregas con {@link android.app.Notification.Builder#addAction(int, java.lang.CharSequence, android.app.PendingIntent) Notification.Builder.addAction()} en botones compactos integrados en las notificaciones de reproducción de medios de la aplicación. Pasa el token de sesión al método {@link android.app.Notification.MediaStyle#setMediaSession(android.media.session.MediaSession.Token) setSession()} para informar al sistema que esta notificación controla una sesión de medios en curso.</p>
+
+<p>Asegúrate de establecer la visibilidad de la notificación en {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC} para marcar la notificación como segura y mostrarla en cualquier pantalla bloqueada (segura o de otra manera). Para obtener más información, consulta <a href="#LockscreenNotifications">Notificaciones de pantalla bloqueada</a>.</p>
+
+<p>Para mostrar los controles de reproducción de medios si la aplicación se está ejecutando en la plataforma de Android <a href="{@docRoot}tv/index.html">TV</a> o Android <a href="{@docRoot}wear/index.html">Wear</a>, implementa la clase {@link android.media.session.MediaSession}. También debes implementar {@link android.media.session.MediaSession} si la aplicación necesita recibir eventos de botones de medios en dispositivos Android.</p>
+
+<h3 id="BehaviorGetRecentTasks">Si la aplicación usa getRecentTasks()…</h3>
+
+<p>Con la introducción de la nueva función de <em>tareas de documentos y actividades concurrentes</em> en Android 5.0 (consulta <a href="#Recents">Documentos y actividades concurrentes en la pantalla de actividades y tareas recientes</a> a continuación), el método {@link android.app.ActivityManager#getRecentTasks ActivityManager.getRecentTasks()} ahora está obsoleto para mejorar la privacidad del usuario. En el caso de la compatibilidad con versiones anteriores, este método sigue devolviendo un pequeño subconjunto de sus datos, que incluye algunas tareas propias de la aplicación que llama y, posiblemente, algunas otras tareas no confidenciales (como Página principal). Si la aplicación usa este método para recuperar sus propias tareas, usa {@link android.app.ActivityManager#getAppTasks() getAppTasks()} en su lugar para recuperar esa información.</p>
+
+<h3 id="64BitSupport">Si usas el kit de desarrollo nativo (NDK) de Android…</h3>
+
+<p>Android 5.0 introduce compatibilidad con sistemas de 64 bits. La mejora de 64 bits aumenta el espacio de direcciones y mejora el rendimiento, al mismo tiempo que mantiene la compatibilidad absoluta con las aplicaciones de 32 bits existentes. La compatibilidad con 64 bits también mejora el rendimiento de OpenSSL para la criptografía. Además, esta versión introduce nuevas API de NDK de medios nativas, así como compatibilidad nativa con la OpenGL ES (GLES) 3.1.</p>
+
+<p>Para usar la compatibilidad con 64 bits proporcionada en Android 5.0, descarga e instala la revisión 10c de NDK desde la <a href="{@docRoot}tools/sdk/ndk/index.html">página de NDK de Android</a>. Consulta las <a href="{@docRoot}tools/sdk/ndk/index.html#Revisions">notas de la versión</a> de la revisión 10c para obtener más información acerca de los cambios y las correcciones de errores importantes en el NDK.</p>
+
+<h3 id="BindService">Si la aplicación se vincula a un servicio…</h3>
+
+<p>El método {@link android.content.Context#bindService(android.content.Intent, android.content.ServiceConnection, int) Context.bindService()} ahora requiere un {@link android.content.Intent} explícito y genera una excepción si se realiza un intento implícito. Para asegurarte de que la aplicación sea segura, usa un intento explícito al iniciar o vincular tu {@link android.app.Service}, y no declares filtros de intención para el servicio.</p>
+
+<h3 id="BehaviorWebView">Si la aplicación usa WebView…</h3>
+
+<p>Android 5.0 cambia el comportamiento predeterminado de la aplicación.</p>
+<ul>
+<li><strong>Si la aplicación está destinada para el nivel de API 21 o un nivel posterior:</strong>
+ <ul>
+ <li>El sistema bloquea <a href="https://developer.mozilla.org/en-US/docs/Security/MixedContent" class="external-link">contenido mixto</a> y cookies de terceros de forma predeterminada. Para permitir contenido mixto y cookies de terceros, usa los métodos {@link android.webkit.WebSettings#setMixedContentMode(int) setMixedContentMode()} y {@link android.webkit.CookieManager#setAcceptThirdPartyCookies(android.webkit.WebView, boolean) setAcceptThirdPartyCookies()}, respectivamente.</li>
+ <li>El sistema ahora elige inteligentemente partes del documento HTML para dibujar. Este nuevo comportamiento predeterminado ayuda a reducir la superficie de memoria y a aumentar el rendimiento. Si quieres representar todo el documento a la vez, inhabilita esta optimización llamando a {@link android.webkit.WebView#enableSlowWholeDocumentDraw()}.</li>
+ </ul>
+</li>
+<li><strong>Si la aplicación está destinada para los niveles de API anteriores a 21:</strong> El sistema permite contenido mixto y cookies de terceros, y siempre representa todo el documento a la vez.</li>
+</ul>
+
+<h2 id="UI">Interfaz de usuario</h2>
+
+<h3 id="MaterialDesign">Compatibilidad con diseño de materiales</h3>
+
+<p>La próxima versión agrega compatibilidad con el nuevo estilo de <em>diseño de materiales</em> de Android. Puedes crear aplicaciones con diseño de materiales que sean visualmente dinámicas y tengan transiciones de elementos de interfaz de usuario que parezcan reales para los usuarios. Esta compatibilidad incluye lo siguiente:</p>
+
+<ul>
+
+ <li>tema de material;</li>
+ <li>sombras de vista;</li>
+ <li>widget {@link android.support.v7.widget.RecyclerView};</li>
+ <li>animación dibujable y efectos de estilo;</li>
+ <li>animación de diseño de materiales y efectos de transición de actividad;</li>
+ <li>animadores para propiedades de vista en función del estado de la vista;</li>
+ <li>widgets de interfaz de usuario personalizables y barras de aplicaciones con paletas de colores que se pueden controlar;</li>
+ <li>dibujables animados y no animados en función de gráficos con vectores XML.</li>
+</ul>
+
+<p>Para obtener más información sobre la adición de la funcionalidad de diseño de materiales a la aplicación, consulta <a href="{@docRoot}training/material/index.html">Diseño de materiales</a>.</p>
+
+<h3 id="Recents">Documentos y actividades concurrentes en la pantalla de actividades y tareas recientes</h3>
+
+<p>En versiones anteriores, la <a href="{@docRoot}guide/components/recents.html">pantalla de actividades y tareas recientes</a> solo podía mostrar una tarea para cada aplicación con la que el usuario había interaccionado recientemente. Si es necesario, ahora la aplicación puede abrir más tareas para actividades y documentos concurrentes adicionales. Esta función facilita la multitarea, ya que permite a los usuarios cambiar rápidamente entre las actividades y los documentos individuales de la pantalla de actividades y tareas recientes, y brinda una experiencia de cambio uniforme entre todas las aplicaciones. Algunos ejemplos de este tipo de tareas concurrentes pueden incluir pestañas abiertas en una aplicación de navegador web, documentos en una aplicación de productividad, partidos concurrentes en un juego o chats en una aplicación de mensajería. La aplicación puede administrar sus tareas a través de la clase {@link android.app.ActivityManager.AppTask}.</p>
+
+<p>Para insertar un salto lógico a fin de que el sistema trate la actividad como una nueva tarea, usa {@link android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT} al iniciar la actividad con {@link android.app.Activity#startActivity(android.content.Intent) startActivity()}. También puedes obtener este comportamiento estableciendo el atributo {@code documentLaunchMode} del elemento de <a href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;actividad&gt;</a> en {@code "intoExisting"} o {@code "always"} en tu manifiesto.</p>
+
+<p>Para evitar la saturación de la pantalla de actividades y tareas recientes, puedes establecer la cantidad máxima de tareas de la aplicación que pueden aparecer en esa pantalla. Para hacerlo, establece el atributo {@link android.R.attr#maxRecents android:maxRecents} de la <a href="{@docRoot}guide/topics/manifest/application-element.html">&lt;aplicación&gt;</a>. La cantidad máxima actual que se puede especificar es de 50 tareas por usuario (25 para dispositivos con baja memoria RAM).</a></p>
+
+<p>Las tareas en la pantalla de actividades y tareas recientes se pueden configurar para que se mantengan tras los reinicios. Para controlar el comportamiento de persistencia, usa el atributo <a href="{@docRoot}reference/android/R.attr.html#persistableMode">android:persistableMode</a>. También puedes cambiar las propiedades visuales de una actividad en la pantalla de actividades y tareas recientes, como el color, la etiqueta y el ícono de la actividad, llamando al método {@link android.app.Activity#setTaskDescription(android.app.ActivityManager.TaskDescription) setTaskDescription()}.</p>
+
+<h3 id="WebView">Actualizaciones de WebView</h3>
+<p>Android 5.0 actualiza la implementación de {@link android.webkit.WebView} a Chromium M37, que incorpora mejoras de seguridad y estabilidad, así como correcciones de errores. Se actualizó la cadena de usuario-agente predeterminada de una {@link android.webkit.WebView} que se ejecuta en Android 5.0 para incorporar 37.0.0.0 como el número de versión.</p>
+
+<p>Esta versión introduce la clase {@link android.webkit.PermissionRequest}, que permite a la aplicación conceder el permiso {@link android.webkit.WebView} para acceder a los recursos protegidos, como la cámara y el micrófono, a través de las API web, como <a href="https://developer.mozilla.org/en-US/docs/NavigatorUserMedia.getUserMedia" class="external-link">getUserMedia()</a>. La aplicación debe tener los permisos apropiados de Android para estos recursos con el fin de otorgar los permisos a {@link android.webkit.WebView}.</p>
+
+<p>Con el nuevo método <code><a href="{@docRoot}reference/android/webkit/WebChromeClient.html#onShowFileChooser(android.webkit.WebView, android.webkit.ValueCallback<android.net.Uri[]>, android.webkit.WebChromeClient.FileChooserParams)">onShowFileChooser()</a></code>, ahora puedes usar un campo de formulario de entrada en {@link android.webkit.WebView} y abrir un selector de archivos para seleccionar imágenes y archivos desde el dispositivo Android.</p>
+
+<p>Además, esta versión admite los estándares abiertos <a href="http://webaudio.github.io/web-audio-api/" class="external-link">WebAudio</a>, <a href="https://www.khronos.org/webgl/" class="external-link">WebGL</a> y <a href="http://www.webrtc.org/" class="external-link">WebRTC</a>. Para obtener más información sobre las nuevas funciones incluidas en esta versión, consulta <a href="https://developer.chrome.com/multidevice/webview/overview" class="external-link">WebView para Android</a>.</p>
+
+<h3 id="ScreenCapture">Captura y uso compartido de pantalla</h3>
+<p>Android 5.0 permite agregar capacidades de captura y uso compartido de pantalla a la aplicación con las nuevas API {@link android.media.projection}. Esta funcionalidad es útil, por ejemplo, si quieres habilitar el uso compartido de la pantalla en una aplicación de videoconferencia.</p>
+
+<p>El nuevo método {@link android.media.projection.MediaProjection#createVirtualDisplay(java.lang.String, int, int, int, int, android.view.Surface, android.hardware.display.VirtualDisplay.Callback, android.os.Handler) createVirtualDisplay()} permite que la aplicación capture el contenido de la pantalla principal (la pantalla predeterminada) en un objeto {@link android.view.Surface}, que luego la aplicación puede enviar a través de la red. La API solo permite capturar contenido de pantalla no seguro, y no audio del sistema. Para comenzar la captura de pantalla, la aplicación primero debe solicitar el permiso del usuario abriendo un cuadro de diálogo de captura de pantalla con un {@link android.content.Intent} obtenido a través del método {@link android.media.projection.MediaProjectionManager#createScreenCaptureIntent()}.</p>
+
+<p>Para ver un ejemplo de cómo utilizar las nuevas API, consulta la clase {@code MediaProjectionDemo} en el proyecto de ejemplo.</p>
+
+<h2 id="Notifications">Notificaciones</h2>
+
+<h3 id="LockscreenNotifications">Notificaciones de pantalla bloqueada</h3>
+<p>Las pantallas bloqueadas en Android 5.0 tienen la capacidad de presentar notificaciones. Los usuarios pueden elegir mediante la <em>configuración</em> si desean permitir que el contenido de notificación confidencial se muestre a través de una pantalla bloqueada segura.</p>
+
+<p>La aplicación puede controlar el nivel de detalle visible cuando las notificaciones se muestran a través de la pantalla bloqueada segura. Para controlar el nivel de visibilidad, llama a {@link android.app.Notification.Builder#setVisibility(int) setVisibility()} y especifica uno de estos valores:</p>
+
+<ul>
+<li>{@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}: Muestra información básica, como el ícono de la notificación, pero oculta el contenido completo de la notificación.</li>
+<li>{@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}: Muestra el contenido completo de la notificación.</li>
+<li>{@link android.app.Notification#VISIBILITY_SECRET VISIBILITY_SECRET}: No muestra nada y excluye incluso el ícono de la notificación.</li>
+</ul>
+
+<p>Cuando el nivel de visibilidad es {@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}, también puedes proporcionar una versión redactada del contenido de la notificación que oculta datos personales. Por ejemplo, una aplicación de SMS podría mostrar una notificación que te indique que tienes tres nuevos mensajes de texto, pero oculta el contenido y los remitentes del mensaje. Para proporcionar esta notificación alternativa, primero crea la notificación de reemplazo utilizando {@link android.app.Notification.Builder}. Cuando crees el objeto de notificación privado, adjúntale la notificación de reemplazo a través del método {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()}.</p>
+
+<h3 id="NotificationsMetadata">Metadatos de notificaciones</h3>
+<p>Android 5.0 utiliza metadatos asociados con notificaciones de la aplicación para ordenar las notificaciones de forma más inteligente. Para definir los metadatos, llama a los siguientes métodos en {@link android.app.Notification.Builder} cuando creas la notificación:</p>
+
+<ul>
+<li>{@link android.app.Notification.Builder#setCategory(java.lang.String) setCategory()}: Indica al sistema cómo manejar las notificaciones de la aplicación cuando el dispositivo está en modo de <em>prioridad</em> (por ejemplo, si una notificación representa una llamada entrante, un mensaje instantáneo o una alarma).
+<li>{@link android.app.Notification.Builder#setPriority(int) setPriority()}: Marca la notificación como más o menos importante que las notificaciones habituales. Las notificaciones con el campo de prioridad establecido en {@link android.app.Notification#PRIORITY_MAX PRIORITY_MAX} o {@link android.app.Notification#PRIORITY_HIGH PRIORITY_HIGH} aparecen en una pequeña ventana flotante si la notificación también tiene sonido o vibración.</li>
+<li>{@link android.app.Notification.Builder#addPerson(java.lang.String) addPerson()}: Permite agregar una o más personas que son relevantes para una notificación. La aplicación puede usar esta opción para indicar al sistema que debería agrupar las notificaciones de las personas especificadas o clasificar las notificaciones de estas personas como más importantes.</li>
+</ul>
+
+<h2 id="Graphics">Gráficos</h2>
+
+<h3 id="OpenGLES-3-1">Compatibilidad con OpenGL ES 3.1</h3>
+<p>Android 5.0 agrega interfaces Java y compatibilidad nativa para OpenGL ES 3.1. La nueva funcionalidad clave proporcionada en OpenGL ES 3.1 incluye lo siguiente:</p>
+
+<ul>
+<li>sombreadores de cálculo;
+<li>objetos de sombreadores independientes;
+<li>comandos de dibujo indirectos;
+<li>texturas de símbolos y multimuestra;
+<li>mejoras del lenguaje de sombreado;
+<li>extensiones para depuración y modos de fusión avanzados;
+<li>compatibilidad de versiones anteriores con OpenGL ES 2.0 y 3.0.
+</ul>
+
+<p>La interfaz Java para OpenGL ES 3.1 en Android se proporciona con {@link android.opengl.GLES31}. Al usar OpenGL ES 3.1, asegúrate de declararlo en el archivo de manifiesto con la etiqueta <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> y el atributo {@code android:glEsVersion}. Por ejemplo:</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:glEsVersion="0x00030001" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<p>Para obtener más información sobre el uso de OpenGL ES, incluso cómo comprobar la versión de OpenGL ES compatible del dispositivo en el tiempo de ejecución, consulta la <a href="{@docRoot}guide/topics/graphics/opengl.html">guía de la API OpenGL ES</a>.</p>
+
+<h3 id="AndroidExtensionPack">Android Extension Pack</h3>
+
+<p>Además de OpenGL ES 3.1, esta versión ofrece un paquete de extensiones con interfaces Java y compatibilidad nativa para la funcionalidad de gráficos avanzada. Estas extensiones se tratan como un solo paquete en Android. (Si la extensión {@code ANDROID_extension_pack_es31a} está presente, la aplicación puede asumir que todas las extensiones en el paquete están presentes y habilitar las funciones del lenguaje de sombreado con una sola instrucción {@code #extension}).</p>
+
+<p>El paquete de extensiones admite lo siguiente:</p>
+
+<ul>
+<li>compatibilidad con sombreador de fragmento garantizada para búferes de almacenamiento de sombreador, imágenes y operaciones atómicas (la compatibilidad con el sombreador de fragmento es opcional en OpenGL ES 3.1);</li>
+<li>sombreadores de geometría y teselación;</li>
+<li>formato de compresión de texturas ASTC (LDR);</li>
+<li>interpolación y sombreado por muestra;</li>
+<li>diferentes modos de fusión para cada archivo adjunto de color en un búfer de fotogramas.</li>
+</ul>
+
+<p>La interfaz Java para el paquete de extensiones se proporciona con {@link android.opengl.GLES31Ext}. En el manifiesto de la aplicación, puedes declarar que la aplicación debe instalarse solo en dispositivos compatibles con el paquete de extensiones. Por ejemplo:</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:name=“android.hardware.opengles.aep”
+ android:required="true" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<h2 id="Media">Medios</h2>
+
+<h3 id="Camera-v2">API de cámara para capacidades avanzadas de la cámara</h3>
+
+<p>Android 5.0 introduce la nueva API <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">android.hardware.camera2</a> para facilitar la captura y el procesamiento de imágenes de grano fino. Ahora puedes acceder mediante programación a los dispositivos de cámara disponibles para el sistema con {@link android.hardware.camera2.CameraManager#getCameraIdList() getCameraIdList()} y conectarte a un dispositivo específico con {@link android.hardware.camera2.CameraManager#openCamera(java.lang.String, android.hardware.camera2.CameraDevice.StateCallback, android.os.Handler) openCamera()}. Para iniciar la captura de imágenes, crea una {@link android.hardware.camera2.CameraCaptureSession} y especifica los objetos {@link android.view.Surface} para enviar las imágenes capturadas. La {@link android.hardware.camera2.CameraCaptureSession} puede configurarse para tomar fotos individuales o múltiples imágenes al instante.</p>
+
+<p>Para recibir una notificación cuando se capturan imágenes nuevas, implementa el agente de escucha {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} y establécelo en la solicitud de captura. Cuando el sistema completa la solicitud de captura de imágenes, el agente de escucha {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} recibe una llamada en {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback#onCaptureCompleted(android.hardware.camera2.CameraCaptureSession, android.hardware.camera2.CaptureRequest, android.hardware.camera2.TotalCaptureResult) onCaptureCompleted()} y proporciona los metadatos de captura de imágenes en un {@link android.hardware.camera2.CaptureResult}.</p>
+
+<p>La clase {@link android.hardware.camera2.CameraCharacteristics} permite que la aplicación detecte las funciones de la cámara que están disponibles en un dispositivo. La propiedad {@link android.hardware.camera2.CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL INFO_SUPPORTED_HARDWARE_LEVEL} del objeto representa el nivel de funcionalidad de la cámara.</p>
+
+<ul>
+ <li>Todos los dispositivos admiten al menos el nivel de hardware {@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY}, que tiene capacidades similares a las de la API {@link android.hardware.Camera} obsoleta.</li>
+ <li>Los dispositivos que admiten el nivel de hardware {@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_FULL INFO_SUPPORTED_HARDWARE_LEVEL_FULL} permiten el control manual de la captura y el procesamiento posterior, así como la captura de imágenes de alta resolución a altas velocidades de fotogramas.</li>
+</ul>
+
+<p>Para ver cómo utilizar la API de la <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">cámara</a> actualizada, consulta las muestras de implementación de {@code Camera2Basic} y {@code Camera2Video} en esta versión.</p>
+
+<h3 id="AudioPlayback">Reproducción de audio</h3>
+<p>En esta versión, se incluyen los cambios a {@link android.media.AudioTrack} que se indican a continuación:</p>
+<ul>
+ <li>La aplicación ahora puede suministrar datos de audio en formato de punto flotante ({@link android.media.AudioFormat#ENCODING_PCM_FLOAT ENCODING_PCM_FLOAT}). Esta función permite obtener un rango dinámico mayor, una precisión más coherente y una capacidad de aumento mayor. La aritmética de punto flotante es especialmente útil durante los cálculos intermedios. Los puntos finales de reproducción usan un formato de enteros para datos de audio con una profundidad en bits inferior. (En Android 5.0, las partes de la canalización interna todavía no son puntos flotantes).
+ <li>La aplicación ahora puede suministrar datos de audio como un {@link java.nio.ByteBuffer} en el mismo formato que proporciona {@link android.media.MediaCodec}.
+ <li>La opción {@link android.media.AudioTrack#WRITE_NON_BLOCKING WRITE_NON_BLOCKING} puede simplificar el almacenamiento en búfer y los subprocesos para algunas aplicaciones.
+</ul>
+
+<h3 id="MediaPlaybackControl">Control de reproducción de medios</h3>
+<p>Usa las nuevas API de notificación y medios para asegurarte de que la interfaz de usuario del sistema sepa cuando reproduces medios y pueda extraer y mostrar la carátula del álbum. El control de la reproducción de medios en una interfaz de usuario y un servicio es ahora más fácil con las nuevas clases {@link android.media.session.MediaSession} y {@link android.media.session.MediaController}.</p>
+
+<p>La nueva clase {@link android.media.session.MediaSession} reemplaza la clase {@link android.media.RemoteControlClient} obsoleta y proporciona un único conjunto de métodos de devolución de llamada para el manejo de los controles de transporte y los botones de los medios. Si la aplicación permite reproducir medios y se ejecuta en la plataforma Android <a href="{@docRoot}tv/index.html">TV</a> o Android <a href="{@docRoot}wear/index.html">Wear</a>, usa la clase {@link android.media.session.MediaSession} para manejar los controles de transporte con los mismos métodos de devolución de llamada.</p>
+
+<p>Ahora puedes crear tu propia aplicación de controlador de medios con la nueva clase {@link android.media.session.MediaController}. Esta clase ofrece una manera segura para subprocesos de supervisar y controlar la reproducción de medios desde el proceso de la interfaz de usuario de la aplicación. Al crear un controlador, especifica un objeto {@link android.media.session.MediaSession.Token} para que la aplicación pueda interaccionar con la {@link android.media.session.MediaSession} dada. Mediante el uso de los métodos {@link android.media.session.MediaController.TransportControls}, puedes enviar comandos, como {@link android.media.session.MediaController.TransportControls#play() play()}, {@link android.media.session.MediaController.TransportControls#stop() stop()}, {@link android.media.session.MediaController.TransportControls#skipToNext() skipToNext()} y {@link android.media.session.MediaController.TransportControls#setRating(android.media.Rating) setRating()}, para controlar la reproducción de medios en esa sesión. Con el controlador, también puedes registrar un objeto {@link android.media.session.MediaController.Callback} para escuchar metadatos y cambios de estado en la sesión.</p>
+
+<p>Además, puedes crear notificaciones enriquecidas que permiten el control de la reproducción vinculado a una sesión de medios con la nueva clase {@link android.app.Notification.MediaStyle}.</p>
+
+<h3 id="MediaBrowsing">Exploración de medios</h3>
+<p>Android 5.0 introduce la capacidad para las aplicaciones de explorar la biblioteca de contenidos de medios de otra aplicación a través de la nueva API <a href="{@docRoot}reference/android/media/browse/package-summary.html">android.media.browse</a>. Para exponer el contenido de los medios en la aplicación, amplía la clase {@link android.service.media.MediaBrowserService}. La implementación de {@link android.service.media.MediaBrowserService} debe proporcionar acceso a {@link android.media.session.MediaSession.Token} para que las aplicaciones puedan reproducir contenido de medios proporcionado a través de tu servicio.</p>
+<p>Para interaccionar con un servicio de explorador de medios, usa la clase {@link android.media.browse.MediaBrowser}. Especifica el nombre del componente para una {@link android.media.session.MediaSession} cuando creas una instancia {@link android.media.browse.MediaBrowser}. El uso de esa instancia de explorador hará que la aplicación pueda conectarse al servicio asociado y obtener un objeto {@link android.media.session.MediaSession.Token} para reproducir contenido expuesto a través de ese servicio.</p>
+
+<h2 id="Storage">Almacenamiento</h2>
+
+<h3 id="DirectorySelection">Selección de directorio</h3>
+
+<p>Android 5.0 amplía el <a href="{@docRoot}guide/topics/providers/document-provider.html">Storage Access Framework</a> para permitir a los usuarios seleccionar un subárbol entero del directorio y proporcionar a las aplicaciones acceso de lectura o escritura a todos los documentos incluidos sin requerir la confirmación del usuario para cada elemento.</p>
+
+<p>Para seleccionar un subárbol del directorio, crea y envía un intento {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE OPEN_DOCUMENT_TREE}. El sistema muestra todas las instancias {@link android.provider.DocumentsProvider} que admiten la selección de subárbol y permite que el usuario explore y seleccione un directorio. El URI devuelto representa el acceso al subárbol seleccionado. A continuación, puedes usar {@link android.provider.DocumentsContract#buildChildDocumentsUriUsingTree(android.net.Uri, java.lang.String) buildChildDocumentsUriUsingTree()} y {@link android.provider.DocumentsContract#buildDocumentUriUsingTree(android.net.Uri, java.lang.String) buildDocumentUriUsingTree()} junto con {@link android.content.ContentResolver#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String) query()} para explorar el subárbol.</p>
+
+<p>El nuevo método {@link android.provider.DocumentsContract#createDocument(android.content.ContentResolver, android.net.Uri, java.lang.String, java.lang.String) createDocument()} permite crear nuevos documentos o directorios en cualquier lugar del subárbol. Para administrar los documentos existentes, usa {@link android.provider.DocumentsContract#renameDocument(android.content.ContentResolver, android.net.Uri, java.lang.String) renameDocument()} y {@link android.provider.DocumentsProvider#deleteDocument(java.lang.String) deleteDocument()}. Comprueba {@link android.provider.DocumentsContract.Document#COLUMN_FLAGS COLUMN_FLAGS} para verificar si el proveedor admite estas llamadas antes de su emisión.</p>
+
+<p>Si implementas un {@link android.provider.DocumentsProvider} y quieres admitir la selección de subárbol, implementa {@link android.provider.DocumentsProvider#isChildDocument(java.lang.String, java.lang.String) isChildDocument()} e incluye {@link android.provider.DocumentsContract.Root#FLAG_SUPPORTS_IS_CHILD FLAG_SUPPORTS_IS_CHILD} en tu {@link android.provider.DocumentsContract.Root#COLUMN_FLAGS COLUMN_FLAGS}.</p>
+
+<p>Android 5.0 también introduce nuevos directorios específicos de paquetes en almacenamiento compartido, donde la aplicación puede colocar archivos de medios para que sean incluidos en {@link android.provider.MediaStore}. El nuevo {@link android.content.Context#getExternalMediaDirs()} devuelve rutas a estos directorios en todos los dispositivos de almacenamiento compartido. De forma similar a {@link android.content.Context#getExternalFilesDir(java.lang.String) getExternalFilesDir()}, la aplicación no necesita permisos adicionales para acceder a las rutas devueltas. La plataforma busca periódicamente nuevos medios en estos directorios, pero tú también puedes utilizar {@link android.media.MediaScannerConnection} para buscar contenido nuevo de forma explícita.</p>
+
+<h2 id="Wireless">Redes inalámbricas y conectividad</h2>
+
+<h3 id="Multinetwork">Múltiples conexiones de red</h3>
+<p>Android 5.0 ofrece nuevas API de múltiples redes que permiten que la aplicación busque las redes disponibles con capacidades específicas dinámicamente y que establezca una conexión con ellas. Esta funcionalidad es útil cuando la aplicación requiere una red especializada, como una red de facturación del operador de telefonía celular, SUPL o MMS, o si quieres enviar datos con un determinado tipo de protocolo de transporte.</p>
+
+<p>Para seleccionar una red y conectarte a ella de forma dinámica desde la aplicación, sigue estos pasos:</p>
+
+<ol>
+ <li>Crea un {@link android.net.ConnectivityManager}.</li>
+ <li>Usa la clase {@link android.net.NetworkRequest.Builder} para crear un objeto {@link android.net.NetworkRequest} y especifica las características de la red y el tipo de transporte que requiere la aplicación.</li>
+<li>Para buscar las redes adecuadas, llama a {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} o {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()}, y envía el objeto {@link android.net.NetworkRequest} y una implementación de {@link android.net.ConnectivityManager.NetworkCallback}. Usa el método {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} si deseas cambiar de forma activa a una red adecuada una vez que se detecta; para recibir solamente notificaciones de redes analizadas sin tener que cambiar de forma activa de red, usa el método {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()} en su lugar.</li>
+</ol>
+
+<p>Cuando el sistema detecta una red adecuada, se conecta a la red e invoca la devolución de llamada {@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()}. Puedes usar el objeto {@link android.net.Network} de la devolución de llamada para obtener información adicional acerca de la red o para indicar que el tráfico use la red seleccionada.</p>
+
+<h3 id="BluetoothBroadcasting">Bluetooth de baja energía</h3>
+<p>Android 4.3 introdujo compatibilidad de plataforma para <a href="{@docRoot}guide/topics/connectivity/bluetooth-le.html">Bluetooth de baja energía</a> (<em>Bluetooth LE</em>) en el rol central. En Android 5.0, un dispositivo Android ahora puede actuar como un <em>dispositivo periférico</em> Bluetooth LE. Las aplicaciones pueden utilizar esta capacidad para que otros dispositivos cercanos detecten su presencia. Por ejemplo, puedes crear aplicaciones que permiten que un dispositivo funcione como un podómetro o un monitor de estado, y comunique sus datos a otro dispositivo Bluetooth LE.</p>
+<p>Las nuevas API {@link android.bluetooth.le} permiten a sus aplicaciones transmitir anuncios, buscar respuestas y establecer conexiones con dispositivos Bluetooth LE cercanos. Para utilizar las nuevas funciones de anuncio y búsqueda, agrega el permiso {@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN} en el manifiesto. Cuando los usuarios actualizan o descargan tu aplicación desde Play Store, se les pide que concedan el siguiente permiso a tu aplicación: "Información de conexión Bluetooth: Permite que la aplicación controle Bluetooth, incluida la transmisión de información a dispositivos Bluetooth cercanos o la obtención de información sobre ellos".</p>
+
+<p>Para comenzar el anuncio de Bluetooth LE a fin de que otros dispositivos puedan detectar tu aplicación, llama a {@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()} y envía una implementación de la clase {@link android.bluetooth.le.AdvertiseCallback}. El objeto de devolución de llamada recibe un informe del éxito o fracaso de la operación de anuncio.</p>
+
+<p> Android 5.0 introduce la clase {@link android.bluetooth.le.ScanFilter} para que tu aplicación pueda buscar solo tipos específicos de dispositivos que le interesan. Para empezar a buscar dispositivos Bluetooth LE, llama a {@link android.bluetooth.le.BluetoothLeScanner#startScan(android.bluetooth.le.ScanCallback) startScan()} y envía una lista de filtros. En la llamada del método, también debes proporcionar una implementación de {@link android.bluetooth.le.ScanCallback} para infomar cuando se encuentra un anuncio de Bluetooth LE. </p>
+
+<h3 id="NFCEnhancements">Mejoras de NFC</h3>
+<p>Android 5.0 agrega estas mejoras para permitir un uso más amplio y más flexible de la NFC:</p>
+
+<ul>
+<li>Android Beam ahora está disponible en el menú de <em>uso compartido</em>.</li>
+<li>La aplicación puede invocar Android Beam en el dispositivo del usuario para compartir datos llamando a {@link android.nfc.NfcAdapter#invokeBeam(android.app.Activity) invokeBeam()}. Esto evita que el usuario tenga que apoyar manualmente el dispositivo contra otro dispositivo NFC para completar la transferencia de datos.</li>
+<li>Puedes utilizar el nuevo método {@link android.nfc.NdefRecord#createTextRecord(java.lang.String, java.lang.String) createTextRecord()} para crear un registro NDEF que contenga datos de texto UTF-8.</li>
+<li>Si programas una aplicación de pago, ahora tienes la capacidad de registrar un ID de aplicación NFC (AID) dinámicamente llamando a <code><a href="{@docRoot}reference/android/nfc/cardemulation/CardEmulation.html#registerAidsForService(android.content.ComponentName, java.lang.String, java.util.List<java.lang.String>)">registerAidsForService()</a></code>. También puedes usar {@link android.nfc.cardemulation.CardEmulation#setPreferredService(android.app.Activity, android.content.ComponentName) setPreferredService()} para establecer el servicio de emulación de tarjeta preferido que se debe utilizar cuando una actividad específica está en primer plano.</li>
+</ul>
+
+<h2 id="Power">Proyecto Volta</h2>
+
+<p>Además de las nuevas funciones, Android 5.0 hace hincapié en las mejoras de la duración de la batería. Usa las nuevas API y la herramienta para entender y optimizar el consumo de energía de la aplicación.</p>
+
+<h3 id="JobScheduler">Programación de trabajos</h3>
+<p>Android 5.0 proporciona una nueva API {@link android.app.job.JobScheduler} que permite optimizar la duración de la batería mediante la definición de trabajos que el sistema ejecutará de forma asíncrona (en otro momento) o en condiciones específicas (por ejemplo, cuando el dispositivo se está cargando). La programación de trabajos es útil en situaciones como las siguientes:</p>
+<ul>
+ <li>La aplicación tiene trabajos en segundo plano que puedes posponer.</li>
+ <li>La aplicación tiene trabajos que prefieres hacer cuando la unidad está enchufada.</li>
+ <li>La aplicación tiene una tarea que requiere acceso a la red o una conexión Wi-Fi.</li>
+ <li>La aplicación tiene una serie de tareas que deseas que se ejecuten como un lote en un horario regular.</li>
+
+</ul>
+
+<p>Una unidad de trabajo está encapsulada por un objeto {@link android.app.job.JobInfo}. Este objeto especifica los criterios de programación.</p>
+
+<p>Usa la clase {@link android.app.job.JobInfo.Builder} para configurar cómo se debe ejecutar la tarea programada. Puedes programar la tarea para que se ejecute en condiciones específicas, como las siguientes:</p>
+
+<ul>
+ <li>Debe empezar cuando el dispositivo se está cargando.</li>
+ <li>Debe empezar cuando el dispositivo está conectado a una red no medida.</li>
+ <li>Debe empezar cuando el dispositivo está inactivo.</li>
+ <li>Debe terminar antes de que transcurra un determinado plazo o con una demora mínima.</li>
+</ul>
+
+<p>Por ejemplo, puedes agregar un código como este para ejecutar la tarea en una red no medida:</p>
+
+<pre>
+JobInfo uploadTask = new JobInfo.Builder(mJobId,
+ mServiceComponent /* JobService component */)
+ .setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED)
+ .build();
+JobScheduler jobScheduler =
+ (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
+jobScheduler.schedule(uploadTask);
+</pre>
+
+<p>Si el dispositivo tiene energía estable (es decir, el dispositivo estuvo enchufado durante más de dos minutos, y la batería está en un <a href="{@docRoot}reference/android/content/Intent.html#ACTION_BATTERY_OKAY">nivel aceptable</a>), el sistema ejecutará cualquier trabajo programado que esté listo, incluso si la fecha límite del trabajo no pasó.</p>
+
+<p>Para ver un ejemplo de cómo utilizar la API {@link android.app.job.JobScheduler}, consulta la muestra de implementación de {@code JobSchedulerSample} en esta versión.</p>
+
+<h3 id="PowerMeasurementTools">Herramientas de programadores para el uso de la batería</h3>
+
+<p>El nuevo comando {@code dumpsys batterystats} genera información estadística interesante sobre el uso de la batería en un dispositivo, organizada por ID de usuario único (UID). Las estadísticas incluyen:</p>
+
+<ul>
+<li>historial de eventos relacionados con la batería;
+<li>estadísticas globales para el dispositivo;
+<li>uso de energía aproximado por UID y componente de sistema;
+<li>ms por paquete de dispositivos móviles por aplicación;
+<li>estadísticas globales de UID de sistema;
+<li>estadísticas globales de UID de aplicación.
+</ul>
+
+<p>Usa la opción {@code --help} para conocer acerca de las diversas opciones que tienes para adaptar la salida. Por ejemplo, para imprimir las estadísticas de uso de la batería de un paquete de aplicaciones dado desde que el dispositivo se cargó por última vez, ejecuta este comando:
+<pre>
+$ adb shell dumpsys batterystats --charged &lt;package-name&gt;
+</pre>
+
+<p>Puedes utilizar la herramienta <a href="https://github.com/google/battery-historian" class="external-link">Battery Historian</a> en la salida del comando {@code dumpsys} para generar una visualización HTML de eventos relacionados con la energía a partir de los registros. Esta información facilita la comprensión y el diagnóstico de cualquier problema relacionado con la batería.</p>
+
+<h2 id="Enterprise">Android en el entorno de trabajo y en el entorno educativo</h2>
+<h3 id="ManagedProvisioning">Aprovisionamiento administrado</h3>
+
+<p>Android 5.0 ofrece nuevas funcionalidades para ejecutar aplicaciones en un entorno empresarial. Un <a href="{@docRoot}guide/topics/admin/device-admin.html">administrador de dispositivos</a> puede iniciar un proceso de aprovisionamiento administrado para agregar un <em>perfil administrado</em> copresente, pero separado, a un dispositivo si el usuario tiene una cuenta personal existente. Las aplicaciones que se asocian con perfiles administrados aparecen junto con las aplicaciones no administradas en el Launcher del usuario, la pantalla de actividades y tareas recientes, y las notificaciones.</p>
+
+<p>Para iniciar el proceso de aprovisionamiento administrado, envía {@link android.app.admin.DevicePolicyManager#ACTION_PROVISION_MANAGED_PROFILE ACTION_PROVISION_MANAGED_PROFILE} en un {@link android.content.Intent}. Si la llamada se realiza correctamente, el sistema activa la devolución de llamada {@link android.app.admin.DeviceAdminReceiver#onProfileProvisioningComplete(android.content.Context, android.content.Intent) onProfileProvisioningComplete()}. A continuación, puedes llamar a {@link android.app.admin.DevicePolicyManager#setProfileEnabled(android.content.ComponentName) setProfileEnabled()} para habilitar este perfil administrado.</p>
+
+<p>De forma predeterminada, solo un pequeño subconjunto de aplicaciones están habilitadas en el perfil administrado. Puedes instalar aplicaciones adicionales en el perfil administrado llamando a {@link android.app.admin.DevicePolicyManager#enableSystemApp(android.content.ComponentName, android.content.Intent) enableSystemApp()}.</p>
+
+<p>Si programas una aplicación Launcher, puedes utilizar la nueva clase {@link android.content.pm.LauncherApps} para obtener una lista de las actividades que se pueden iniciar para el usuario actual y los perfiles administrados asociados. El Launcher puede hacer que las aplicaciones administradas sean visualmente prominentes agregando una insignia de trabajo al ícono dibujable. Para recuperar el ícono con insignia, llama a {@link android.content.pm.PackageManager#getUserBadgedIcon(android.graphics.drawable.Drawable, android.os.UserHandle) getUserBadgedIcon()}.</p>
+
+<p>Para ver cómo utilizar la nueva funcionalidad, consulta la muestra de implementación de {@code BasicManagedProfile} en esta versión.</p>
+
+<h3 id="DeviceOwner">Propietario de dispositivo</h3>
+<p>Android 5.0 introduce la capacidad de implementar una aplicación de propietario de dispositivo. Un <em>propietario de dispositivo</em> es un tipo especializado de <a href="{@docRoot}guide/topics/admin/device-admin.html">administrador de dispositivos</a> que tiene la capacidad adicional de crear y eliminar usuarios secundarios, y configurar opciones globales en el dispositivo. La aplicación de propietario de dispositivo puede utilizar los métodos de la clase {@link android.app.admin.DevicePolicyManager} para tomar un control específico de la configuración, la seguridad y las aplicaciones en los dispositivos administrados. Un dispositivo puede tener solamente un propietario de dispositivo activo a la vez.</p>
+
+<p>Para implementar y activar un propietario de dispositivo, debes realizar una transferencia de datos NFC desde una aplicación de programación hasta el dispositivo mientras el dispositivo está en estado no aprovisionado. Esta transferencia de datos envía la misma información que la que se envía en el intento de aprovisionamiento descrito en <a href="#ManagedProvisioning">Aprovisionamiento administrado</a>.</p>
+
+<h3 id="ScreenPinning">Fijación de pantalla</h3>
+
+<p>Android 5.0 introduce una nueva API para fijar la pantalla que te permite impedir temporalmente que los usuarios salgan de tu tarea o sean interrumpidos por notificaciones. Podría usarse, por ejemplo, si estás programando una aplicación de educación para cumplir con requisitos de evaluación de gran importancia en Android o una aplicación de único propósito o kiosco. Una vez que la aplicación activa la fijación de pantalla, los usuarios no pueden ver las notificaciones, acceder a otras aplicaciones ni volver a la pantalla principal hasta que la aplicación sale del modo.</p>
+
+<p>Hay dos formas de activar la fijación de pantalla:</p>
+
+<ul>
+<li><strong>Manualmente:</strong> Los usuarios pueden habilitar la fijación de pantalla desde <em>Configuración &gt; Seguridad&gt; Fijar pantalla</em> y seleccionar las tareas que desean fijar tocando el ícono para fijar de color verde en la pantalla de actividades y tareas recientes.</li> <li><strong>Mediante programación</strong>: Para activar la fijación de pantalla mediante programación, llama a {@link android.app.Activity#startLockTask() startLockTask()} desde la aplicación. Si la aplicación que realiza la solicitud no es un propietario de dispositivo, se solicita confirmación al usuario. Una aplicación de propietario de dispositivo puede llamar al método {@link android.app.admin.DevicePolicyManager#setLockTaskPackages(android.content.ComponentName, java.lang.String[]) setLockTaskPackages()} para permitir que las aplicaciones se puedan fijar sin tener que pasar por el paso de confirmación del usuario.</li>
+</ul>
+
+<p>Cuando el bloqueo de tarea está activo, ocurre lo siguiente:</p>
+
+<ul>
+<li>La barra de estado está en blanco, y las notificaciones de los usuarios y la información de estado están ocultas.</li>
+<li>Los botones de pantalla principal y aplicaciones recientes están ocultos.</li>
+<li>Otras aplicaciones no pueden iniciar actividades nuevas.</li>
+<li>La aplicación actual puede iniciar actividades nuevas, siempre y cuando no cree nuevas tareas.</li>
+<li>Cuando la fijación de pantalla es invocada por un propietario de dispositivo, el usuario no puede acceder a tu aplicación hasta que la aplicación llama a {@link android.app.Activity#stopLockTask() stopLockTask()}.</li>
+<li>Si la fijación de pantalla es una actividad realizada por otra aplicación que no es un propietario de dispositivo o por el usuario directamente, el usuario puede salir de ella manteniendo presionados los botones de retroceso y aplicaciones recientes.</li>
+
+</ul>
+
+<h2 id="Printing">Marco de impresión</h2>
+
+<h3 id="PDFRender">Representación de PDF como mapa de bits</h3>
+<p>Ahora puedes representar páginas de documentos PDF en imágenes de mapa de bits para imprimir mediante el uso de la nueva clase {@link android.graphics.pdf.PdfRenderer}. Debes especificar un {@link android.os.ParcelFileDescriptor} que admita búsquedas (es decir, que se pueda acceder al contenido de forma aleatoria) y en el que el sistema pueda escribir el contenido imprimible. La aplicación puede obtener una página para representar con {@link android.graphics.pdf.PdfRenderer#openPage(int) openPage()} y luego llamar a {@link android.graphics.pdf.PdfRenderer.Page#render(android.graphics.Bitmap, android.graphics.Rect, android.graphics.Matrix, int) render()} para convertir la {@link android.graphics.pdf.PdfRenderer.Page} abierta en un mapa de bits. También puedes configurar parámetros adicionales si solo deseas convertir una parte del documento en una imagen de mapa de bits (por ejemplo, para implementar la <a href="http://en.wikipedia.org/wiki/Tiled_rendering" class="external-link">representación en mosaicos</a> a fin de hacer zoom en el documento).</p>
+
+<p>Para ver un ejemplo de cómo utilizar las nuevas API, consulta la muestra {@code PdfRendererBasic}.</p>
+
+<h2 id="System">Sistema</h2>
+<h3 id="AppUsageStatistics">Estadísticas de uso de aplicaciones</h3>
+<p>Ahora puedes acceder al historial de uso de las aplicaciones desde un dispositivo Android con la nueva API {@link android.app.usage}. Esta API proporciona información de uso más detallada que el método {@link android.app.ActivityManager#getRecentTasks(int, int) getRecentTasks()} obsoleto. Para utilizar esta API, primero debes declarar el permiso {@code "android.permission.PACKAGE_USAGE_STATS"} en el manifiesto. El usuario también debe permitir el acceso a esta aplicación a través de <em>Configuración &gt; Seguridad&gt; Aplicaciones</em> con acceso de uso.</p>
+
+<p>El sistema recopila los datos de uso por aplicación y agrega los datos en intervalos diarios, semanales, mensuales y anuales. El tiempo máximo que el sistema conserva estos datos es el siguiente:</p>
+
+<ul>
+ <li>datos diarios: siete días;</li>
+ <li>datos semanales: cuatro semanas;</li>
+ <li>datos mensuales: seis meses;</li>
+ <li>datos anuales: dos años.</li>
+</ul>
+
+<p>Para cada aplicación, el sistema registra los siguientes datos:</p>
+<ul>
+<li>la última vez que se utilizó la aplicación;</li>
+<li>la cantidad total de tiempo que la aplicación estuvo en primer plano durante ese intervalo (por día, semana, mes o año);</li>
+<li>captura de marca de tiempo del momento en que un componente (identificado por un nombre de actividad y paquete) se trasladó a primer plano o segundo plano durante un día;</li>
+<li>captura de marca de tiempo del momento en que se modificó la configuración de un dispositivo (por ejemplo, cuando la orientación del dispositivo cambió debido a la rotación).</li>
+</ul>
+
+<h2 id="TestingA11y">Pruebas y accesibilidad </h2>
+
+<h3 id="TestingA11yImprovements">Mejoras de pruebas y accesibilidad</h3>
+<p>Android 5.0 incorpora la siguiente compatibilidad para pruebas y accesibilidad:</p>
+
+<ul>
+<li>Los nuevos métodos {@link android.app.UiAutomation#getWindowAnimationFrameStats() getWindowAnimationFrameStats()} y {@link android.app.UiAutomation#getWindowContentFrameStats(int) getWindowContentFrameStats()} capturan estadísticas de fotogramas para animaciones de ventanas y contenido. Estos métodos permiten escribir pruebas de instrumentación para evaluar si una aplicación está representando fotogramas a una frecuencia de actualización suficiente que brinde a los usuarios una experiencia perfecta.</li>
+
+<li>El nuevo método {@link android.app.UiAutomation#executeShellCommand(java.lang.String) executeShellCommand()} permite ejecutar comandos shell desde la prueba de instrumentación. La ejecución de comandos es similar a la ejecución de {@code adb shell} desde un host conectado al dispositivo, lo que permite utilizar herramientas basadas en shell, como {@code dumpsys}, {@code am}, {@code content} y {@code pm}.</li>
+
+<li>Los servicios de accesibilidad y las herramientas de prueba que utilizan las API de accesibilidad (como <a href="{@docRoot}tools/help/uiautomator/index.html">{@code UiAutomator}</a>) ahora pueden recuperar datos precisos acerca de las propiedades de las ventanas en pantalla con las que pueden interaccionar los usuarios videntes. Para recuperar una lista de objetos {@link android.view.accessibility.AccessibilityWindowInfo}, llama al nuevo método {@link android.accessibilityservice.AccessibilityService#getWindows() getWindows()}.</li>
+
+<li>La nueva clase {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} permite definir acciones estándares o personalizadas para realizar en un {@link android.view.accessibility.AccessibilityNodeInfo}. La nueva clase {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} reemplaza las API relacionadas con acciones que se encontraban previamente en {@link android.view.accessibility.AccessibilityNodeInfo}.</li>
+
+<li>Android 5.0 ofrece un control más preciso sobre la síntesis de texto a voz en la aplicación. La nueva clase {@link android.speech.tts.Voice} permite que la aplicación use perfiles de voz asociados con configuraciones regionales específicas, calificaciones de calidad y latencia, y parámetros específicos del motor de conversión de texto a voz.</li>
+</ul>
+
+<h2 id="IME">IME</h2>
+
+<h3 id="Switching">Cambio más sencillo de idiomas de entrada</h3>
+
+<p>A partir de Android 5.0, los usuarios pueden cambiar más fácilmente entre todos los <a href="{@docRoot}guide/topics/text/creating-input-method.html">editores de métodos de entrada (IME)</a> admitidos por la plataforma. La ejecución de la acción de cambio designada (normalmente tocar un ícono del mundo en el teclado en pantalla) te lleva por todos estos IME. Este cambio de comportamiento es implementado por el método {@link android.view.inputmethod.InputMethodManager#shouldOfferSwitchingToNextInputMethod(android.os.IBinder) shouldOfferSwitchingToNextInputMethod()}.</p>
+
+<p>Además, el marco ahora comprueba si el siguiente IME incluye un mecanismo de cambio (y, por lo tanto, si ese IME admite el cambio al IME después de él). Un IME con un mecanismo de cambio no pasará a otro IME que no lo tenga. Este cambio de comportamiento es implementado por el método {@link android.view.inputmethod.InputMethodManager#switchToNextInputMethod(android.os.IBinder, boolean) switchToNextInputMethod()}.
+
+<p>Para ver un ejemplo de cómo utilizar las API de cambio de IME actualizadas, consulta la muestra de implementación de teclado en pantalla actualizada en esta versión. Para obtener más información acerca de cómo implementar el cambio entre los IME, consulta <a href="{@docRoot}guide/topics/text/creating-input-method.html">Creación de un método de entrada</a>.
+</p>
+
+<h2 id="Manifest">Declaraciones de manifiesto</h2>
+
+<h3 id="ManifestFeatures">Características requeridas declarables</h3>
+<p>Los siguientes valores ahora son compatibles con el elemento <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a>, por lo que puedes asegurarte de que la aplicación solo se instale en dispositivos que proporcionen las características que necesita.</p>
+
+<ul>
+<li>{@link android.content.pm.PackageManager#FEATURE_AUDIO_OUTPUT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_POST_PROCESSING}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_SENSOR}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_RAW}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_LEVEL_FULL}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_GAMEPAD}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LIVE_TV}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_MANAGED_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LEANBACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_OPENGLES_EXTENSION_PACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SECURELY_REMOVES_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_AMBIENT_TEMPERATURE}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_HEART_RATE_ECG}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_RELATIVE_HUMIDITY}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_VERIFIED_BOOT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_WEBVIEW}</li>
+</ul>
+
+<h3 id="Permissions">Permisos de usuario</h3>
+
+<p>El siguiente permiso ahora es compatible con el elemento <a href="{@docRoot}guide/topics/manifest/uses-permission-element.html">{@code <uses-permission>}</a> para declarar los permisos que requiere la aplicación para acceder a determinadas API.</p>
+
+<ul>
+<li>{@link android.Manifest.permission#BIND_DREAM_SERVICE}: Cuando se busca un nivel de API 21 o posterior, este permiso es requerido por un servicio de <a href="{@docRoot}about/versions/android-4.2.html#Daydream">Protector de pantalla interactivo</a> para garantizar que solo el sistema pueda vincularse a él.</li>
+</ul>
diff --git a/docs/html-intl/intl/es/about/versions/lollipop.jd b/docs/html-intl/intl/es/about/versions/lollipop.jd
new file mode 100644
index 0000000..2725270
--- /dev/null
+++ b/docs/html-intl/intl/es/about/versions/lollipop.jd
@@ -0,0 +1,249 @@
+page.title=Android Lollipop
+
+@jd:body
+
+
+
+
+
+ <div style="padding:0px 0px 0px 20px;float:right;margin:0 -10px 0 0">
+ <img src="{@docRoot}images/home/l-hero_2x.png" srcset="{@docRoot}images/home/l-hero.png 1x, {@docRoot}images/home/l-hero_2x.png 2x" width="460" height="300" >
+ </div>
+
+ <div class="landing-docs" style="float:right;clear:both;margin:68px 0 2em 3em;">
+ <div class="col-4 normal-links highlights" style="font-size:12px;">
+ <h3 id="thisd" >Funciones clave para programadores</h3>
+ <ul style="list-style-type:none;">
+ <li><a href="#Material">Material design</a></li>
+ <li><a href="#Perf">Enfoque en el rendimiento</a></li>
+ <li><a href="#Notifications">Notificaciones</a></li>
+ <li><a href="#TV">Tus aplicaciones en la pantalla grande</a></li>
+ <li><a href="#Documents">Aplicaciones centradas en el documento</a></li>
+ <li><a href="#Connectivity">Conectividad avanzada</a></li>
+ <li><a href="#Graphics">Gráficos de alto rendimiento</a></li>
+ <li><a href="#Audio">Audio más potente</a></li>
+ <li><a href="#Camera">Cámara y video mejorados</a></li>
+ <li><a href="#Work">Android en el lugar de trabajo</a></li>
+ <li><a href="#ScreenCapture">Captura y uso compartido de pantalla</a></li>
+ <li><a href="#Sensors">Nuevos tipos de sensores</a></li>
+ <li><a href="#WebView">WebView de Chromium</a></li>
+ <li><a href="#Accessibility">Accesibilidad y entrada</a></li>
+ <li><a href="#Battery">Herramientas para aplicaciones con uso eficiente de batería</a></li>
+ </ul>
+ </div>
+</div>
+
+
+
+
+
+
+
+<p>Te damos la bienvenida a Android 5.0 Lollipop, la versión de Android más extensa y ambiciosa hasta el momento.</p>
+
+<p>Esta versión está repleta de funciones nuevas para usuarios y miles de API nuevas para programadores. Android se sigue expandiendo; desde teléfonos, tablets y wearables hasta televisores y autos.</p>
+
+<p>Si quieres conocer las API para programadores más en detalle, consulta la <a href="{@docRoot}about/versions/android-5.0.html">Descripción general de las API de Android 5.0</a>. También puedes obtener más información sobre Android 5.0 para consumidores en <a href="http://www.android.com/versions/lollipop-5-0/">www.android.com</a>.</p>
+
+<h2 id="Material">Material design</h2>
+
+<p>Android 5.0 incluye <a href="http://www.google.com/design/spec">Material design</a> y te ofrece un kit de herramientas expandido para la interfaz de usuario. Con este kit, podrás integrar los nuevos patrones de diseño a las aplicaciones fácilmente. </p>
+
+
+
+<p>Las nuevas <strong>vistas 3D</strong> te permiten establecer un eje z y superponer los elementos en la jerarquía con <strong>sombras en tiempo real</strong>, incluso mientras se mueven.</p>
+
+
+<p>Las <strong>transiciones de actividad</strong> integradas trasladan al usuario de un estado al otro de forma fluida y con un movimiento estético y animado. El tema del material agrega transiciones a las actividades, incluida la capacidad de usar <strong>elementos visuales compartidos</strong> a través de las actividades.</p>
+
+
+
+<div style="width:290px;margin-right:35px;float:left">
+ <div class="framed-nexus5-port-span-5">
+ <video class="play-on-hover" autoplay="">
+ <source src="/design/material/videos/ContactsAnim.mp4">
+ <source src="/design/videos/ContactsAnim.webm">
+ <source src="/design/videos/ContactsAnim.ogv">
+ </video>
+ </div>
+ <div style="font-size:10pt;margin-left:20px;margin-bottom:30px">
+ <em>Para volver a reproducir el video, haz clic en la pantalla del dispositivo.</em>
+ </div>
+</div>
+
+
+<p>Las animaciones con efecto de propagación están disponibles para botones, casillas de verificación y otros controles táctiles de tu aplicación.
+
+<p>También puedes definir elementos de diseño vectoriales en XML y animarlos de distintas formas. Los elementos de diseño vectoriales escalan sin perder definición, por lo que son ideales para los íconos de un solo color integrados en aplicaciones.</p>
+
+<p>Un nuevo grupo de subprocesos de procesamiento administrado por el sistema, llamado <strong>RenderThread</strong>, mantiene las animaciones fluidas incluso cuando hay demoras en el proceso de interfaz de usuario principal. </p>
+
+
+<h2 id="Perf">Enfoque en el rendimiento</h2>
+
+<p>Android 5.0 ofrece una experiencia informática más veloz, más fluida y más potente.</p>
+
+<p>Android ahora se ejecuta exclusivamente en el nuevo <strong>tiempo de ejecución ART</strong>, creado desde cero para ofrecer compatibilidad con una mezcla de ahead-of-time (AOT), just-in-time (JIT) y código interpretado. Admite las arquitecturas ARM, x86 y MIPS, y además es totalmente compatible con la arquitectura de 64 bits.</p>
+
+<p>El tiempo de ejecución ART mejora el rendimiento y la capacidad de respuesta de las aplicaciones. El recolector de basura eficiente reduce la cantidad y la duración de pausas para los eventos de recolección de basura, que encajan sin inconvenientes en la ventana con sincronización vertical para que la aplicación no omita fotogramas. Además, ART traslada memoria de forma dinámica para optimizar el rendimiento durante el uso de elementos en primer plano. </p>
+
+<p>Android 5.0 incluye compatibilidad de plataforma para las <strong>arquitecturas de 64 bits</strong> que usa la placa NVIDIA Tegra K1 de la Nexus 9. Las optimizaciones ofrecen espacios de direcciones más amplios y un rendimiento mejorado para las cargas de trabajo de ciertos procesos. Las aplicaciones que están en lenguaje de Java se ejecutan automáticamente como aplicaciones de 64 bits; no es necesario realizar modificaciones. Si tu aplicación usa código nativo, extendimos el NDK para que sea compatible con las nuevas ABI para ARM v8, x86-64 y MIPS 64.</p>
+
+<p>Continuando con el enfoque en el rendimiento más parejo, Android 5.0 ofrece sincronización A/V mejorada. Los procesos gráficos y de audio se instrumentaron para lograr marcas de tiempo más precisas, lo que permite que las aplicaciones de video y de juegos muestren contenido sincronizado y parejo.</p>
+
+
+<h2 id="Notifications">Notificaciones</h2>
+
+<p>Las notificaciones en Android 5.0 son más visibles, accesibles y configurables. </p>
+
+<img src="{@docRoot}images/versions/notification-headsup.png" style="float:right; margin:0 0 40px 60px" width="300" height="224" />
+
+<p>Pueden aparecer detalles de notificaciones distintos <strong>en la pantalla bloqueada</strong> si el usuario lo desea. Los usuarios pueden elegir si permiten que, en la pantalla bloqueada segura, aparezca todo el contenido las notificaciones, que aparezca parte del contenido o que no aparezca nada. </p>
+
+<p>Las alertas de notificaciones clave, como una llamada entrante, aparecen en una <strong>notificación emergente</strong>, es decir, una ventana flotante pequeña que permite al usuario responder o ignorar la notificación sin abandonar la aplicación que está utilizando.</p>
+
+<p>Ahora puedes agregar <strong>metadatos nuevos</strong> a las notificaciones para recopilar contactos asociados (para la clasificación), categoría y prioridad.</p>
+
+<p>Una nueva plantilla de notificación de contenido multimedia ofrece controles multimedia para las notificaciones con hasta seis botones de acción, incluidos controles personalizados, como "Me gusta". Ya no necesitarás usar RemoteViews.</p>
+
+
+
+<h2 id="TV">Tus aplicaciones en la pantalla grande</h2>
+
+<p><a href="http://developer.android.com/tv/index.html">Android TV</a> te ofrece una plataforma de televisión completa para la experiencia de tu aplicación en la pantalla grande. Android TV se centra en una experiencia simplificada de pantalla principal que permite a los usuarios descubrir contenido fácilmente gracias a las recomendaciones personalizadas y la búsqueda por voz.</p>
+
+<p>Con Android TV, ahora puedes <strong>crear una gran experiencia llena de creatividad</strong> para el contenido de tu aplicación o juego, además de ofrecer compatibilidad para que interaccione con controladores de juegos y otros dispositivos de entrada. Con el fin de ayudarte a crear una interfaz de usuario cinemática, de tres metros para televisión, Android ofrece un <strong>marco de trabajo de la interfaz de usuario Leanback</strong> en la <a href="{@docRoot}tools/support-library/features.html#v17-leanback">versión 17 de la biblioteca de soporte</a>.</p>
+
+<p>El <strong>marco de trabajo de entrada de televisión de Android</strong> (TIF) permite que las aplicaciones de televisión manejen las transmisiones de video desde distintas fuentes, como entradas HDMI, sintonizadores de televisión y receptores IPTV. También permite la búsqueda y las recomendaciones de televisión en vivo a través de metadatos publicados por la entrada de televisión e incluye el Servicio de control HDMI-CEC para manejar múltiples dispositivos con un solo control remoto. </p>
+
+<p>El marco de trabajo de entrada de televisión ofrece acceso a una amplia variedad de fuentes entrada de televisión en vivo. Además, las reúne en una sola interfaz de usuario para que estos puedan explorar, ver y disfrutar el contenido. Crear un servicio de entrada de televisión para tu contenido puede ayudar a que sea más accesible en los dispositivos de televisión.</p>
+
+
+
+<img src="{@docRoot}images/versions/recents_screen_2x.png" srcset="{@docRoot}images/versions/recents_screen.png 1x, {@docRoot}images/versions/recents_screen_2x.png 2x" style="float:right; margin:0 0 40px 60px" width="300" height="521" />
+
+<h2 id="Documents">Aplicaciones centradas en el documento</h2>
+
+<p>Android 5.0 presenta un espacio rediseñado de la sección Recientes; mucho más versátil y útil para tareas múltiples.</p>
+
+<p>Las nuevas API permiten mostrar actividades separadas en tu aplicación como documentos individuales junto a otras pantallas recientes.</p>
+
+<p>Puedes aprovechar los documentos concurrentes para darles a los usuarios la posibilidad de acceder al instante a más contenidos o servicios tuyos. Por ejemplo, podrías usar los documentos concurrentes para representar archivos en una aplicación de productividad, partidos de un jugador en un juego o chats en una aplicación de mensajería. </p>
+
+
+
+<h2 id="Connectivity">Conectividad avanzada</h2>
+
+<p>Android 5.0 agrega nuevas API que permiten que las aplicaciones realicen operaciones concurrentes con <strong>Bluetooth de baja energía</strong> (BLE), lo que permite la detección (modo central) y la publicidad (modo periférico).</p>
+
+<p>Las nuevas funciones de <strong>redes múltiples</strong> permiten que las aplicaciones realicen consultas a las redes disponibles sobre las funciones disponibles, por ejemplo, si son redes Wi-Fi, móviles o de uso medido, o si ofrecen ciertas funciones de red. Luego, la aplicación puede solicitar una conexión y responder a la pérdida de conectividad o a otros cambios en la red.</p>
+
+<p>Las API de <strong>NFC</strong> ahora permiten que las aplicaciones registren un ID de aplicación NFC (AID) de forma dinámica. También pueden establecer el servicio de emulación de tarjeta preferido por servicio activo y crear un registro NDEF que contenga datos de texto UTF-8.</p>
+
+
+
+<h2 id="Graphics">Gráficos de alto rendimiento</h2>
+
+<p>La compatibilidad con <strong><a href="http://www.khronos.org/opengles/3_X/">OpenGL ES 3.1 de Khronos</a></strong> ahora permite que los juegos y las aplicaciones cuenten con la capacidad gráfica en 2D y 3D de más alto rendimiento en dispositivos admitidos. </p>
+
+<p>OpenGL ES 3.1 incluye sombreadores de cálculo, texturas de símbolos, efectos visuales con aceleración, compresión de texturas ETC2/EAC de alta calidad, procesamiento de texturas avanzado, formatos renderbuffer y tamaño de textura estandarizados, y muchas cosas más.</p>
+
+
+<div class="figure" style="width:350px; margin:0 0 0 60px">
+<img src="{@docRoot}images/versions/rivalknights.png" style="float:right;" width="350" height="525" />
+<p class="img-caption">Rival Knights de Gameloft usa compresión de texturas ASTC (Adaptive Scalable Texture Compression) de AEP y sombreadores de cálculo de ES 3.1 para brindar efectos bloom/HDR y gráficos más detallados.</p>
+</div>
+
+<p>Android 5.0 también presenta el <strong>paquete de extensiones de Android</strong> (AEP), un conjunto de extensiones de OpenGL ES que permiten acceder a funciones como sombreadores de teselación y geometría, compresión de texturas ASTC, interpolación y sombreado por muestra y otras capacidades avanzadas de procesamiento. Con AEP, puedes ofrecer gráficos de alto rendimiento a través de una gran variedad de GPU.</p>
+
+
+<h2 id="Audio">Audio más potente</h2>
+
+<p>Un nuevo diseño de captura de audio ofrece <strong>entrada de audio de baja latencia</strong>. El nuevo diseño incluye: un subproceso de captura rápida que nunca se bloquea, excepto durante una lectura; clientes de captura rápida a una tasa nativa de muestra, recuento de canales y profundidad de bits. Los clientes normales de captura ofrecen remuestreo y la opción de aumentar o disminuir la mezcla de canales o la profundidad de bit.</p>
+
+<p>La <strong>mezcla de transmisión de audio</strong> de canales múltiples permite que las aplicaciones de audio profesionales mezclen hasta ocho canales, incluidos los canales 5.1 y 7.1.</p>
+
+<p>Las aplicaciones pueden exponer su contenido multimedia y <strong>explorar el contenido multimedia</strong> de otras aplicaciones y luego solicitar reproducción. El contenido se expone a través de una interfaz consultable y no necesita residir en el dispositivo.</p>
+
+<p>Las aplicaciones tienen un control más preciso de la <strong>síntesis de texto a voz</strong> mediante perfiles de voz asociados con idiomas específicos, calidad y tasa de latencia. Las nuevas API también mejoran compatibilidad con la comprobación de errores de síntesis, la síntesis de la red, la detección de idiomas y la reserva de red.</p>
+
+<p>Android ahora incluye compatibilidad con los periféricos de <strong>audio USB</strong> estándar, lo que permite a los usuarios conectar auriculares USB, altavoces, micrófonos u otros periféricos digitales de alto rendimiento. Android 5.0 también agrega compatibilidad con códecs de audio <strong>Opus</strong>.</p>
+
+<p>Gracias a las nuevas API <strong>{@link android.media.session.MediaSession}</strong> para controlar la reproducción de contenido multimedia, ahora es más sencillo brindar controles multimedia consistentes en todas las pantallas y en otros controladores.</p>
+
+
+<h2 id="Camera">Cámara y video mejorados</h2>
+
+<p>Android 5.0 presenta <strong>API de la cámara totalmente nuevas</strong> que te permiten capturar formatos sin procesar, como YUV y Bayer RAW, y controlar distintos parámetros, como el tiempo de exposición, la sensibilidad ISO y la duración de una toma cuadro por cuadro. Los nuevos procesos totalmente sincronizados de la cámara te permiten capturar imágenes YUV sin comprimir y en su resolución original a 30&nbsp;FPS en dispositivos compatibles.</p>
+
+<p>Además de las imágenes, también puedes capturar metadatos de la cámara, como modelos de ruido e información óptica.</p>
+
+<p>Las aplicaciones que envían transmisiones de video por redes ahora pueden aprovechar el estándar H.265 <strong>High Efficiency Video Coding (HEVC)</strong> para lograr la codificación y decodificación optimizadas de los datos de video. </p>
+
+<p>Android 5.0 también agrega compatibilidad con la <strong>tunelización de contenido multimedia</strong> para ofrecer la mejor experiencia de contenido con ultraalta definición (4K) y la posibilidad de reproducir datos de audio y video comprimidos al mismo tiempo. </p>
+
+
+
+<div class="figure" style="width:320px; margin:1em 0 0 20px;padding-left:2em;">
+<img style="float:right; margin:0 1em 1em 2em" src="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png" srcset="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png 2x" alt="" width="300" />
+<p class="img-caption">Los usuarios tienen una visión unificada de sus aplicaciones personales y laborales, las cuales tienen una insignia para identificarlas fácilmente.</p>
+</div>
+
+
+<h2 id="Work">Android en el lugar de trabajo</h2>
+
+<p>Para habilitar la política de traer tu propio dispositivo en entornos empresariales, un <a href="{@docRoot}about/versions/android-5.0.html#Enterprise">proceso de aprovisionamiento administrado</a> se encarga de crear un perfil seguro de trabajo en el dispositivo. En el Launcher, las aplicaciones aparecen con una insignia de Work para indicar que un administrador de TI administra la aplicación y sus datos dentro del perfil de trabajo.</p>
+
+<p>Notificaciones tanto del perfil personal y como del laboral son visibles en una vista unificada. Los datos de cada perfil se mantienen siempre seguros y separados entre sí, incluso cuando ambos perfiles usan la misma aplicación.</p>
+
+<p>En el caso de dispositivos que son propiedad de la empresa, los administradores de TI pueden comenzar con un nuevo dispositivo y configurarlo con un <a href="{@docRoot}about/versions/android-5.0.html#DeviceOwner">propietario de dispositivo</a>. Los empleadores pueden entregar estos dispositivos con una aplicación de propietario de dispositivo ya instalada que pueda ajustar la configuración general del dispositivo.</p>
+
+
+
+<h2 id="ScreenCapture">Captura y uso compartido de pantalla</h2>
+
+<p>Android 5.0 te permite agregar capacidades de captura y uso compartido de pantalla a tu aplicación. </p>
+
+<p>Con el permiso del usuario, puedes capturar video no seguro de la pantalla y distribuirlo en la red si lo deseas.</p>
+
+
+<h2 id="Sensors">Nuevos tipos de sensores</h2>
+
+<p>En Android 5.0, un nuevo sensor <strong>detector de inclinación</strong> ayuda a mejorar el reconocimiento de la actividad en los dispositivos compatibles, y un <strong>sensor de frecuencia cardíaca</strong> informa del ritmo cardíaco de la persona que toca el dispositivo. </p>
+
+<p>Los nuevos <strong>sensores compuestos de interacción</strong> ahora están disponibles para detectar interacciones especiales, por ejemplo, cuando el usuario hace un gesto para <em>activar</em> el dispositivo, <em>levantarlo</em> o <em>mirarlo</em>.</p>
+
+
+
+<h2 id="WebView">WebView de Chromium</h2>
+
+<div style="float:right;margin:1em 2em 1em 2em;">
+ <img src="/images/kk-chromium-icon.png" alt="" height="160" style="margin-bottom:0em;">
+</div>
+
+<p>La versión inicial de Android 5.0 incluye una versión de Chromium para {@link android.webkit.WebView} basada en la versión M37 de Chromium, y con ella se agrega compatibilidad con <strong>WebRTC</strong>, <strong>WebAudio</strong> y <strong>WebGL</strong>. </p>
+
+<p>Chromium M37 también incluye compatibilidad nativa para todas las especificaciones de los <strong>Web Components</strong>: Custom Elements, Shadow DOM, HTML Imports y Templates. Esto significa que puedes usar <a href="http://polymer-project.org/">Polymer</a> y sus <a href="https://www.polymer-project.org/docs/elements/material.html">elementos de diseño material</a> en una WebView sin polyfills.</p>
+
+<p>A pesar de que WebView se basó en Chromium desde Android 4.4, ahora se puede actualizar la capa de Chromium desde Google Play.</p>
+
+<p>A medida que haya más versiones disponibles de Chromium, los usuarios podrán actualizar la suya desde Google Play para asegurarse de que tienen las mejoras y correcciones de errores más recientes para WebView, además de encontrar las últimas API web y correcciones de errores para las aplicaciones que usen WebView en Android 5.0 y versiones posteriores.</p>
+
+
+
+<h2 id="Accessibility">Accesibilidad y entrada</h2>
+
+<p>Las nuevas API de accesibilidad pueden recuperar información detallada sobre las propiedades de las ventanas en la pantalla con la que los usuarios videntes pueden interactuar y definir acciones de entrada estándar o personalizadas para distintos elementos de la interfaz de usuario.</p>
+
+<p>La nueva API de editor de método de entrada (IME) permite cambiar en menos tiempo a otros editores directamente desde el método de entrada.</p>
+
+
+
+<h2 id="Battery">Herramientas para crear aplicaciones con uso eficiente de batería</h2>
+
+<p>Las nuevas API de <strong>programación de tareas</strong> te permiten optimizar la duración de la batería gracias a la opción para postergar tareas que el sistema ejecutará más tarde o bajo condiciones específicas, por ejemplo, cuando el dispositivo se está cargando o conectado a Wi-Fi.</p>
+
+<p>Un nuevo comando <code>dumpsys batterystats</code> genera <strong>estadísticas de uso de batería</strong> que puedes utilizar para comprender el uso de la batería en todo el sistema y el impacto de tu aplicación en la batería del dispositivo. Puedes consultar un historial de eventos de energía, el uso aproximado de energía por en una historia de eventos de energía, el uso de energía aproximado por identificador único de usuario (UID) y componente del sistema, y muchas opciones más.</p>
+
+<img src="{@docRoot}images/versions/battery_historian.png" srcset="{@docRoot}images/versions/battery_historian@2x.png 2x" alt="" width="760" height="462" />
+<p class="img-caption">Battery Historian es una nueva herramienta para convertir las estadísticas de <code>dumpsys batterystats</code> en una visualización de la depuración relacionada con la batería. Encuentra esta herramienta en <a href="https://github.com/google/battery-historian">https://github.com/google/battery-historian</a>.</p>
diff --git a/docs/html-intl/intl/ja/about/versions/android-5.0.jd b/docs/html-intl/intl/ja/about/versions/android-5.0.jd
new file mode 100644
index 0000000..47cd24d
--- /dev/null
+++ b/docs/html-intl/intl/ja/about/versions/android-5.0.jd
@@ -0,0 +1,635 @@
+page.title=Android 5.0 API
+excludeFromSuggestions=true
+sdk.platform.version=5.0
+sdk.platform.apiLevel=21
+@jd:body
+
+
+<div id="qv-wrapper">
+<div id="qv">
+
+<h2>このドキュメントの内容 <a href="#" onclick="hideNestedItems('#toc44',this);return false;" class="header-toggle"> <span class="more">詳細を表示</span> <span class="less" style="display:none">詳細を隠す</span></a></h2>
+
+<ol id="toc44" class="hide-nested">
+ <li><a href="#ApiLevel">対象 API レベルの更新</a></li>
+ <li><a href="#Behaviors">動作に関する重要な変更</a>
+ <ol>
+ <li><a href="#ART">まだ新しい Android Runtime(ART)に対してアプリをテストしていない場合</a></li>
+ <li><a href="#BehaviorNotifications">アプリで通知を実装する場合</a></li>
+ <li><a href="#BehaviorMediaControl">アプリで RemoteControlClient を使用する場合</a></li>
+<li><a href="#BehaviorGetRecentTasks">アプリで getRecentTasks() を使用する場合</a></li>
+<li><a href="#64BitSupport">Android Native Development Kit(NDK)を使用している場合</a></li>
+<li><a href="#BindService">アプリからサービスにバインドする場合</a></li>
+<li><a href="#BehaviorWebView">アプリで WebView を使用する場合</a></li>
+ </ol>
+ </li>
+ <li><a href="#UI">ユーザー インターフェース</a>
+ <ol>
+ <li><a href="#MaterialDesign">Material Design のサポート</a></li>
+ <li><a href="#Recents">最近使ったアプリ画面に表示される同時実行中のドキュメント / アクティビティ</a></li>
+ <li><a href="#WebView">WebView の更新</a></li>
+ <li><a href="#ScreenCapture">画面のキャプチャと共有</a></li>
+ </ol>
+ </li>
+ <li><a href="#Notifications">通知</a>
+ <ol>
+ <li><a href="#LockscreenNotifications">ロック画面の通知</a></li>
+ <li><a href="#NotificationsMetadata">通知メタデータ</a></li>
+ </ol>
+ </li>
+ <li><a href="#Graphics">グラフィック</a>
+ <ol>
+ <li><a href="#OpenGLES-3-1">OpenGL ES 3.1 のサポート</a></li>
+ <li><a href="#AndroidExtensionPack">Android Extension Pack</a></li>
+ </ol>
+ </li>
+ <li><a href="#Media">メディア</a>
+ <ol>
+ <li><a href="#Camera-v2">高度なカメラ機能に対応した Camera API</a></li>
+ <li><a href="#AudioPlayback">音声の再生</a></li>
+ <li><a href="#MediaPlaybackControl">メディア再生コントロール</a></li>
+ <li><a href="#MediaBrowsing">メディアの参照</a></li>
+ </ol>
+ </li>
+ <li><a href="#Storage">ストレージ</a>
+ <ol>
+ <li><a href="#DirectorySelection">ディレクトリの選択</a></li>
+ </ol>
+ </li>
+ <li><a href="#Wireless">ワイヤレスと接続</a>
+ <ol>
+ <li><a href="#Multinetwork">マルチネットワーク接続</a></li>
+ <li><a href="#BluetoothBroadcasting">Bluetooth によるブロードキャスト</a></li>
+ <li><a href="#NFCEnhancements">NFC の機能強化</a></li>
+ </ol>
+ </li>
+ <li><a href="#Power">Project Volta</a>
+ <ol>
+ <li><a href="#JobScheduler">ジョブのスケジューリング</a></li>
+ <li><a href="#PowerMeasurementTools">電池の使用統計情報を提供するデベロッパー向けツール</a>
+ </ol>
+ </li>
+ <li><a href="#Enterprise">職場向けや教育向けの Android</a>
+ <ol>
+ <li><a href="#ManagedProvisioning">管理対象プロビジョニング</a></li>
+ <li><a href="#DeviceOwner">端末所有者</a></li>
+ <li><a href="#ScreenPinning">画面の固定</a></li>
+ </ol>
+ </li>
+ <li><a href="#System">システム</a>
+ <ol>
+ <li><a href="#AppUsageStatistics">アプリの使用統計情報</a></li>
+ </ol>
+ </li>
+ <li><a href="#Printing">印刷フレームワーク</a>
+ <ol>
+ <li><a href="#PDFRender">PDF をビットマップとしてレンダリング</a></li>
+ </ol>
+ </li>
+ <li><a href="#TestingA11y">テストとユーザー補助</a>
+ <ol>
+ <li><a href="#TestingA11yImprovements">テストとユーザー補助の向上</a></li>
+ </ol>
+ </li>
+ <li><a href="#IME">IME</a>
+ <ol>
+ <li><a href="#Switching">入力言語の切り替えやすさの向上</a></li>
+ </ol>
+ </li>
+ <li><a href="#Manifest">マニフェスト宣言</a>
+ <ol>
+ <li><a href="#ManifestFeatures">宣言可能な必須機能</a></li>
+ <li><a href="#Permissions">ユーザー権限</a></li>
+ </ol>
+ </li>
+</ol>
+
+<h2>API Differences</h2>
+<ol>
+<li><a href="{@docRoot}sdk/api_diff/21/changes.html">API level 20 to 21 &raquo;</a> </li>
+<li><a href="{@docRoot}sdk/api_diff/preview-21/changes.html">L Developer Preview to 21 &raquo;</a> </li>
+</ol>
+
+<h2>See Also</h2>
+<ol>
+<li><a href="{@docRoot}about/versions/android-5.0-changes.html">Android 5.0 Behavior Changes</a> </li>
+<li><a href="{@docRoot}about/versions/lollipop.html">Android Lollipop Highlights</a> </li>
+</ol>
+
+</div>
+</div>
+
+<p>API レベル: {@sdkPlatformApiLevel}</p>
+
+<p>Android 5.0(<a href="{@docRoot}reference/android/os/Build.VERSION_CODES.html#LOLLIPOP">Lollipop</a>)は、ユーザーとアプリ デベロッパーに新しい機能を提供します。このドキュメントでは、最も重要な新しい API を紹介しています。</p>
+
+<p>新しいプラットフォーム機能の概要について詳しくは、<a href="{@docRoot}about/versions/lollipop.html">Android Lollipop の特長</a>をご覧ください。</p>
+
+
+<h3 id="Start">開発の開始</h3>
+
+<p>Android 5.0 対応アプリの開発を始めるには、最初に <a href="{@docRoot}sdk/index.html">Android SDK を入手する</a>必要があります。次に、<a href="{@docRoot}tools/help/sdk-manager.html">SDK Manager</a> を使用して Android 5.0 SDK プラットフォームとシステム イメージをダウンロードします。</p>
+
+<h3 id="ApiLevel">対象 API レベルの更新</h3>
+
+<p>Android {@sdkPlatformVersion} 搭載端末向けにアプリの最適化を向上させるには、<a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> を <code>"{@sdkPlatformApiLevel}"</code> に設定し、Android {@sdkPlatformVersion} システム イメージにアプリをインストールした後、この変更を加えた更新済みのアプリを公開します。</p>
+
+<p>Android {@sdkPlatformVersion} API を使用しながら旧バージョンも同時にサポートするには、<a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> でサポートされていない API を実行する前に、システムの API レベルをチェックする条件をコードに追加します。下位互換性の維持について詳しくは、<a href="{@docRoot}training/basics/supporting-devices/platforms.html">複数のプラットフォーム バージョンへの対応</a>をご覧ください。</p>
+
+<p>API レベルの仕組みについて詳しくは、<a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">API レベルとは</a>をご覧ください。</p>
+
+<h2 id="Behaviors">動作に関する重要な変更</h2>
+
+<p>以前に Android 対応アプリを公開したことがある場合は、アプリが Android 5.0 の変更による影響を受ける可能性があることに注意してください。</p>
+
+<h3 id="ART">まだ新しい Android Runtime(ART)に対してアプリをテストしていない場合</h3>
+
+<p>リリース 4.4 では新しい Android ランタイムである ART が試験的に導入されていました。4.4 では、ART はオプションで、デフォルトのランタイムは Dalvik のままでした。Android 5.0 では、ART がデフォルトのランタイムになりました。</p>
+
+<p>ART の新機能の概要について詳しくは、<a href="https://source.android.com/devices/tech/dalvik/art.html">ART の紹介</a>をご覧ください。主に次のような新機能があります。</p>
+
+<ul>
+ <li>AOT(Ahead-of-time、事前)コンパイル</li>
+ <li>ガベージ コレクション(GC)の向上</li>
+ <li>デバッグ サポートの向上</li>
+</ul>
+
+<p>ほとんどの Android アプリは変更を加えなくても ART で問題なく動作します。ただし、Dalvik で動作する一部の技術が ART で動作しません。特に重要な問題について詳しくは、<a href="{@docRoot}guide/practices/verifying-apps-art.html">Android Runtime(ART)でアプリの動作を検証する</a>をご覧ください。特に次の点にご注意ください。</p>
+
+<ul>
+ <li>アプリで C/C++ のコードを実行する場合は Java Native Interface(JNI)を使用します。</li>
+ <li>非標準のコードを生成する開発ツール(難読化ツールなど)を使用します。</li>
+ <li>ガベージ コレクションのコンパクションと互換性のない技術を使用します(ART では現在 GC のコンパクションは実装されていませんが、Android オープンソース プロジェクトで GC のコンパクションの開発が進められています)。</li>
+</ul>
+
+<h3 id="BehaviorNotifications">アプリで通知を実装する場合</h3>
+
+<p>通知を実装する際は、Android 5.0 での変更点について必ず考慮してください。Android 5.0 以降に対応した通知の設計について詳しくは、<a href="{@docRoot}design/patterns/notifications.html">通知の設計に関するガイド</a>をご覧ください。
+</p>
+
+<h4 id="NotificationsMaterialDesignStyle">Material Design スタイル</h4>
+<p>通知は、新しい Material Design ウィジェットに合わせて、白色(または非常に明るい色)の背景の上に暗い色のテキストで描かれます。すべての通知が新しい配色で見やすくなるようにしてください。通知が見にくい場合は、次の方法で修正してください。</p>
+
+<ul>
+ <li>{@link android.app.Notification.Builder#setColor(int) setColor()} を使用してアクセントのある色を設定し、その色でアイコン イメージの背後に円を描きます。 </li>
+ <li>色を伴うアセットを更新または削除します。操作アイコンとメインの通知アイコンでは、非アルファ チャンネルはすべて無視されます。これらのアイコンはアルファのみとなることを前提としてください。通知アイコンは白で、操作アイコンは濃いグレーで、それぞれ描かれます。</li>
+</ul>
+
+<h4 id="NotificationsSoundVibration">音声とバイブレーション</h4>
+<p>現在 {@link android.media.Ringtone}、{@link android.media.MediaPlayer}、または {@link android.os.Vibrator} クラスを使用して音声やバイブレーションを通知に追加している場合は、システムが「優先」<em></em>モードで通知を正しく表示できるように、それらのコードを削除してください。代わりに {@link android.app.Notification.Builder} のメソッドを使用して音声やバイブレーションを追加してください。</p>
+
+<p>端末を {@link android.media.AudioManager#RINGER_MODE_SILENT RINGER_MODE_SILENT} に設定すると端末が新しい優先モードになります。端末を {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_NORMAL} または {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_VIBRATE} に設定すると端末の優先モードが終了します。</p>
+
+<p>従来、Android ではタブレット端末のボリュームをコントロールするために {@link android.media.AudioManager#STREAM_MUSIC STREAM_MUSIC} をマスター ストリームとして使用していました。Android 5.0 では、携帯電話とタブレット端末の両方のマスター ボリューム ストリームが統合され、{@link android.media.AudioManager#STREAM_RING STREAM_RING} または {@link android.media.AudioManager#STREAM_NOTIFICATION STREAM_NOTIFICATION} によってコントロールされるようになりました。</p>
+
+<h4 id="NotificationsLockscreenVisibility">ロック画面の表示</h4>
+<p>Android 5.0 ではデフォルトでユーザーのロック画面に通知が表示されるようになりました。ユーザーは機密情報の表示を防ぐことを選択できます。その場合は通知に表示されるテキストが自動的に編集されます。編集される通知をカスタマイズする場合は、{@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()} を使用してください。</p>
+<p>通知に個人情報が含まれていない場合や、通知にメディア再生コントロールを表示できるようにしたい場合は、{@link android.app.Notification.Builder#setVisibility(int) setVisibility()} メソッドを呼び出して通知の表示レベルを {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC} に設定してください。
+</p>
+
+<h4 id="NotificationsMediaPlayback">メディアの再生</h4>
+<p>メディアの再生状態やトランスポート コントロールを表示する通知を実装する場合は、カスタムの {@link android.widget.RemoteViews.RemoteView} オブジェクトに代わって新しい {@link android.app.Notification.MediaStyle} テンプレートを使用することをおすすめします。どちらのアプローチの場合でも、必ず通知の表示を {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC} に設定して、ロック画面からコントロールにアクセスできるようにしてください。Android 5.0 以降では、ロック画面に {@link android.media.RemoteControlClient} オブジェクトが表示されなくなりました。詳しくは、<a href="#BehaviorMediaControl">アプリで RemoteControlClient を使用する場合</a>をご覧ください。</p>
+
+<h4 id="NotificationsHeadsup">警告通知</h4>
+<p>必要に応じて、端末がアクティブのとき(端末のロックが解除されていて画面が表示されているとき)に通知が小さいフローティング ウィンドウ(警告通知ともいいます)に表示されるようになりました。これらの通知の外観はデベロッパーによる簡易形式の通知に似ていますが、警告通知には操作ボタンも表示されます。ユーザーは、現在のアプリから離れることなく警告通知に応答したり、警告通知を拒否したりできます。</p>
+
+<p>たとえば次のような条件の場合に警告通知が起動されることがあります。</p>
+
+<ul>
+ <li>ユーザーのアクティビティが全画面表示モードになっている(アプリで {@link android.app.Notification#fullScreenIntent} を使用している)</li>
+ <li>通知の優先順位が高く、着信音やバイブレーションを使用している</li>
+</ul>
+
+<p>こうした条件の下でアプリで通知を実装する場合は、必ず警告通知が正しく表示されるようにしてください。</p>
+
+<h3 id="BehaviorMediaControl">アプリで RemoteControlClient を使用する場合</h3>
+<p>{@link android.media.RemoteControlClient} クラスは非推奨になりました。できるだけ速やかに新しい {@link android.media.session.MediaSession} API に切り替えてください。</p>
+
+<p>Android 5.0 のロック画面には {@link android.media.session.MediaSession} または {@link android.media.RemoteControlClient} に対応したトランスポート コントロールは表示されません。アプリでは代わりに、通知を通してロック画面からメディア再生コントロールを提供することができます。これにより、メディアボタンの表示をより詳細にコントロールできるようになると同時に、端末のロック時とロック解除時で一貫したユーザー エクスペリエンスが提供されます。</p>
+
+<p>この目的のために、Android 5.0 では新しい {@link android.app.Notification.MediaStyle} テンプレートが導入されています。{@link android.app.Notification.MediaStyle} は、{@link android.app.Notification.Builder#addAction(int, java.lang.CharSequence, android.app.PendingIntent) Notification.Builder.addAction()} で追加した通知操作をコンパクトなボタンに変換し、アプリのメディア再生通知に埋め込みます。セッション トークンを {@link android.app.Notification.MediaStyle#setMediaSession(android.media.session.MediaSession.Token) setSession()} メソッドに渡し、この通知によって以後のメディア セッションがコントロールされることをシステムに伝えます。</p>
+
+<p>必ず通知の表示を {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC} に設定し、どのようなロック画面でも安全に表示できる(それ以外の場合はセキュリティで保護される)ものとしてマークします。詳しくは、<a href="#LockscreenNotifications">ロック画面の通知</a>をご覧ください。</p>
+
+<p>アプリを Android <a href="{@docRoot}tv/index.html">TV</a> または <a href="{@docRoot}wear/index.html">Wear</a> プラットフォームで実行する場合、メディア再生コントロールを表示するには {@link android.media.session.MediaSession} クラスを実装してください。アプリで Android 端末のメディアボタン イベントを受信する必要がある場合は、{@link android.media.session.MediaSession} も実装してください。</p>
+
+<h3 id="BehaviorGetRecentTasks">アプリで getRecentTasks() を使用する場合</h3>
+
+<p>Android 5.0 で新しい「同時実行中のドキュメント / アクティビティ タスク」<em></em>機能が導入されたことに伴い(下記の<a href="#Recents">最近使ったアプリ画面に表示される同時実行中のドキュメント / アクティビティ</a>をご覧ください)、ユーザーのプライバシーを向上させるために {@link android.app.ActivityManager#getRecentTasks ActivityManager.getRecentTasks()} メソッドは非推奨になりました。下位互換性の目的から、このメソッドは引き続きデータの小さなサブセット(呼び出し側アプリの独自のタスクや、他の機密でないタスク(たとえばホーム)など)を返します。アプリで独自のタスクを取得するためにこのメソッドを使用している場合は、代わりに {@link android.app.ActivityManager#getAppTasks() getAppTasks()} を使用してその情報を取得してください。</p>
+
+<h3 id="64BitSupport">Android Native Development Kit(NDK)を使用している場合</h3>
+
+<p>Android 5.0 では 64 ビット システムのサポートが導入されています。64 ビットへの拡大によってアドレス空間が増加し、パフォーマンスが向上します。一方で、既存の 32 ビット アプリについても引き続き完全にサポートされます。また、64 ビットのサポートによって OpenSSL の暗号化のパフォーマンスも向上します。さらに、今回のリリースではネイティブの OpenGL ES(GLES)3.1 のサポートに加えて、新しいネイティブのメディア NDK API も導入されています。</p>
+
+<p>Android 5.0 で提供される 64 ビットのサポートを利用するには、<a href="{@docRoot}tools/sdk/ndk/index.html">Android NDK のページ</a>から NDK Revision 10c をダウンロードしてインストールしてください。NDK の重要な変更点とバグ修正について詳しくは、Revision 10c の<a href="{@docRoot}tools/sdk/ndk/index.html#Revisions">リリースノート</a>をご覧ください。</p>
+
+<h3 id="BindService">アプリからサービスにバインドする場合</h3>
+
+<p>{@link android.content.Context#bindService(android.content.Intent, android.content.ServiceConnection, int) Context.bindService()} メソッドについて、明示的な {@link android.content.Intent} の指定が必須となり、暗黙的なインテントを指定した場合は例外をスローするようになりました。アプリが確実にセキュリティで保護されるように、{@link android.app.Service} の起動やバインドの際は明示的なインテントを使用し、サービスに対してインテント フィルタを宣言しないでください。</p>
+
+<h3 id="BehaviorWebView">アプリが WebView を使用している場合</h3>
+
+<p>Android 5.0 ではアプリのデフォルトの動作が変更されています。</p>
+<ul>
+<li><strong>アプリの対象が API レベル 21 以降の場合:</strong>
+ <ul>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Security/MixedContent" class="external-link">混合コンテンツ</a>とサードパーティの Cookie がデフォルトでブロックされます。混合コンテンツとサードパーティの Cookie を許可するには、それぞれ {@link android.webkit.WebSettings#setMixedContentMode(int) setMixedContentMode()} メソッドと {@link android.webkit.CookieManager#setAcceptThirdPartyCookies(android.webkit.WebView, boolean) setAcceptThirdPartyCookies()} メソッドを使用します。</li>
+ <li>描画する HTML ドキュメントの部分が適切に選択されるようになりました。この新しいデフォルトの動作は、メモリ量の減少とパフォーマンスの向上につながります。ドキュメント全体を一度に表示したい場合は、{@link android.webkit.WebView#enableSlowWholeDocumentDraw()} を呼び出してこの最適化を無効にしてください。</li>
+ </ul>
+</li>
+<li><strong>アプリの対象が API レベル 21 よりも前の場合:</strong> 混合コンテンツとサードパーティの Cookie が許可され、常にドキュメント全体が一度に表示されます。</li>
+</ul>
+
+<h2 id="UI">ユーザー インターフェース</h2>
+
+<h3 id="MaterialDesign">Material Design のサポート</h3>
+
+<p>次期リリースでは、Android の新しい「Material Design」<em></em>スタイルが新たにサポートされます。Material Design を使うと、外観が動的に変化し、ユーザーが UI 要素の切り替えを自然だと感じるようなアプリを作成できます。このサポートには以下が含まれます。</p>
+
+<ul>
+
+ <li>マテリアル テーマ</li>
+ <li>ビューシャドウ</li>
+ <li>{@link android.support.v7.widget.RecyclerView} ウィジェット</li>
+ <li>描画可能なアニメーションとスタイル効果</li>
+ <li>Material Design によるアニメーションとアクティビティ遷移効果</li>
+ <li>ビューの状態に基づいてビューのプロパティを決めるアニメータ</li>
+ <li>カスタマイズ可能な UI ウィジェットと、カラーパレットをコントロールできるアプリバー</li>
+ <li>XML ベクター グラフィックをベースとするアニメーション drawable と非アニメーション drawable</li>
+</ul>
+
+<p>アプリに Material Design の機能を追加する方法について詳しくは、<a href="{@docRoot}training/material/index.html">Material Design</a> をご覧ください。</p>
+
+<h3 id="Recents">最近使ったアプリ画面に表示される同時実行中のドキュメント / アクティビティ</h3>
+
+<p>以前のリリースでは、<a href="{@docRoot}guide/components/recents.html">最近使ったアプリ画面</a>には、ユーザーが最近操作したアプリごとにタスクを 1 つずつしか表示できませんでした。今後は、ドキュメント用の同時実行中のアクティビティが追加される場合、必要に応じて複数のタスクをアプリで開けるようになります。この機能により、ユーザーは最近使ったアプリ画面から個々のアクティビティやドキュメントをすばやく切り替えられるようになります。すべてのアプリにわたって一貫した切り替え操作になるので、マルチタスクの操作がしやすくなります。こうした同時実行中のタスクの例としては、ウェブブラウザ アプリで複数のタブを開く、生産性向上アプリで複数のドキュメントを開く、ゲームで複数の試合を同時に実行する、メッセージ アプリで複数のチャットを実行する、などが考えられます。アプリのタスクは {@link android.app.ActivityManager.AppTask} クラスを使って管理できます。</p>
+
+<p>論理的な切れ目を挿入してアクティビティが新しいタスクとして扱われるようにするには、{@link android.app.Activity#startActivity(android.content.Intent) startActivity()} を使用してアクティビティを起動するときに {@link android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT} を使用します。または、マニフェストで <a href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a> 要素の {@code documentLaunchMode} 属性を {@code "intoExisting"} または {@code "always"} に設定しても、この動作を実現できます。</p>
+
+<p>最近使ったアプリ画面が適切に整理されるように、最近使ったアプリ画面に表示できるタスクの最大数をアプリから設定することができます。それには、<a href="{@docRoot}guide/topics/manifest/application-element.html">&lt;application&gt;</a> 属性 {@link android.R.attr#maxRecents android:maxRecents} を設定します。指定できる現在の最大タスク数はユーザーあたり 50 個(RAM が不足している端末の場合は 25 個)です。</a></p>
+
+<p>最近使ったアプリ画面に表示されるタスクが再起動後も持続されるように設定することができます。この持続動作をコントロールするには <a href="{@docRoot}reference/android/R.attr.html#persistableMode">android:persistableMode</a> 属性を使用します。また、{@link android.app.Activity#setTaskDescription(android.app.ActivityManager.TaskDescription) setTaskDescription()} メソッドを呼び出して、最近使ったアプリ画面に表示されるアクティビティの表示プロパティ(アクティビティの色、ラベル、アイコンなど)を変更することもできます。</p>
+
+<h3 id="WebView">WebView の更新</h3>
+<p>Android 5.0 では Chromium M37 に対する {@link android.webkit.WebView} の実装が更新され、セキュリティと安定性が強化されているほか、バグが修正されています。Android 5.0 で実行される {@link android.webkit.WebView} のデフォルトのユーザーエージェント文字列が更新され、バージョン番号として 37.0.0.0 が組み込まれています。</p>
+
+<p>今回のリリースでは {@link android.webkit.PermissionRequest} クラスが導入されています。アプリでこのクラスを使用することで、<a href="https://developer.mozilla.org/en-US/docs/NavigatorUserMedia.getUserMedia" class="external-link">getUserMedia()</a> などのウェブ API を通じてカメラやマイクなどの保護リソースにアクセスするための権限を {@link android.webkit.WebView} に許可できます。{@link android.webkit.WebView} に権限を許可するためには、これらのリソースに対する適切な Android 権限をアプリに持たせる必要があります。</p>
+
+<p>新しい <code><a href="{@docRoot}reference/android/webkit/WebChromeClient.html#onShowFileChooser(android.webkit.WebView, android.webkit.ValueCallback<android.net.Uri[]>, android.webkit.WebChromeClient.FileChooserParams)">onShowFileChooser()</a></code> メソッドでは、{@link android.webkit.WebView} で入力フォーム項目を使用できるようになり、ファイル選択機能を起動して Android 端末から画像やファイルを選択できるようになりました。</p>
+
+<p>さらに、今回のリリースでは <a href="http://webaudio.github.io/web-audio-api/" class="external-link">WebAudio</a>、<a href="https://www.khronos.org/webgl/" class="external-link">WebGL</a>、<a href="http://www.webrtc.org/" class="external-link">WebRTC</a> の各オープン規格もサポートされるようになります。今回のリリースに含まれる新機能について詳しくは、<a href="https://developer.chrome.com/multidevice/webview/overview" class="external-link">Android 用 WebView</a> をご覧ください。</p>
+
+<h3 id="ScreenCapture">画面のキャプチャと共有</h3>
+<p>Android 5.0 では、新しい {@link android.media.projection} API を使用して画面キャプチャ機能や画面共有機能をアプリに追加できます。この機能は、たとえばビデオ会議アプリで画面の共有を有効にしたい場合などに便利です。</p>
+
+<p>アプリで新しい {@link android.media.projection.MediaProjection#createVirtualDisplay(java.lang.String, int, int, int, int, android.view.Surface, android.hardware.display.VirtualDisplay.Callback, android.os.Handler) createVirtualDisplay()} メソッドを使用すると、メイン画面(デフォルトの表示)の内容をキャプチャして {@link android.view.Surface} オブジェクトに取り込み、アプリからネットワーク経由で送信することができます。API では、セキュリティで保護されていない画面内容のキャプチャのみ可能であり、システム音声のキャプチャはできません。アプリで画面のキャプチャを開始するには、最初に {@link android.media.projection.MediaProjectionManager#createScreenCaptureIntent()} メソッドを通じて取得した {@link android.content.Intent} を使用して画面キャプチャ用のダイアログを起動し、ユーザーの許可をリクエストする必要があります。</p>
+
+<p>新しい API の使用例については、サンプル プロジェクトの {@code MediaProjectionDemo} クラスをご覧ください。</p>
+
+<h2 id="Notifications">通知</h2>
+
+<h3 id="LockscreenNotifications">ロック画面の通知</h3>
+<p>Android 5.0 のロック画面には通知を表示する機能が組み込まれています。ユーザーは [設定]<em></em> を通じて、機密性のある通知内容をセキュリティで保護されたロック画面に表示できるようにするかどうかを選択できます。</p>
+
+<p>アプリでは、セキュリティで保護されたロック画面にアプリの通知が表示されるときの表示の詳細レベルをコントロールできます。表示レベルをコントロールするには、{@link android.app.Notification.Builder#setVisibility(int) setVisibility()} を呼び出して次のいずれかの値を指定します。</p>
+
+<ul>
+<li>{@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}: 通知のアイコンなどの基本的な情報は表示しますが、通知内容全体は表示しません。</li>
+<li>{@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}: 通知内容全体を表示します。</li>
+<li>{@link android.app.Notification#VISIBILITY_SECRET VISIBILITY_SECRET}: 通知のアイコンも含めて何も表示しません。</li>
+</ul>
+
+<p>表示レベルが {@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE} の場合は、詳細な個人情報を隠した編集済みの通知内容を表示することもできます。たとえば SMS アプリで、「3 個の新しいテキスト メッセージがあります」という通知は表示しますが、メッセージの内容や送信者を表示しないようにできます。こうした代わりの通知を表示するには、最初に {@link android.app.Notification.Builder} を使用して代わりとなる通知を作成します。プライベートの通知オブジェクトを作成するときに、{@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()} メソッドを使用して代わりの通知をオブジェクトに添付します。</p>
+
+<h3 id="NotificationsMetadata">通知メタデータ</h3>
+<p>Android 5.0 では、アプリの通知がよりスマートに並べ替えられるように、通知に関連付けられたメタデータが使用されます。メタデータを設定するには、通知の作成時に {@link android.app.Notification.Builder} で次のメソッドを呼び出します。</p>
+
+<ul>
+<li>{@link android.app.Notification.Builder#setCategory(java.lang.String) setCategory()}: 端末が「優先」<em></em>モードのとき(通知が電話の着信、インスタント メッセージ、またはアラームを表している場合など)のアプリでの通知の処理方法をシステムに指示します。
+<li>{@link android.app.Notification.Builder#setPriority(int) setPriority()}: 対象の通知について、通常の通知と比べて重要度が高いことまたは低いことをマークします。優先項目が {@link android.app.Notification#PRIORITY_MAX PRIORITY_MAX} または {@link android.app.Notification#PRIORITY_HIGH PRIORITY_HIGH} に設定された通知は、通知に音声やバイブレーションが付いている場合に、小さいフローティング ウィンドウに表示されます。</li>
+<li>{@link android.app.Notification.Builder#addPerson(java.lang.String) addPerson()}: 通知への関連性がある人を 1 人以上追加できるようにします。アプリでこうしたメソッドを使用することで、指定した人からの通知をグループにまとめる必要があることや、それらの人からの通知をより重要なものとしてランク付けする必要があることを、システムに知らせることができます。</li>
+</ul>
+
+<h2 id="Graphics">グラフィック</h2>
+
+<h3 id="OpenGLES-3-1">OpenGL ES 3.1 のサポート</h3>
+<p>Android 5.0 では、OpenGL ES 3.1 のネイティブ サポートとそれに対応した Java インターフェースが追加されています。OpenGL ES 3.1 では主に次の新機能が提供されています。</p>
+
+<ul>
+<li>コンピュート シェーダ
+<li>個別のシェーダ オブジェクト
+<li>間接描画コマンド
+<li>マルチサンプル テクスチャとステンシル テクスチャ
+<li>シェーディング言語の向上
+<li>高度なブレンドモードとデバッグに対応した拡張機能
+<li>OpenGL ES 2.0 / 3.0 との下位互換性
+</ul>
+
+<p>Android での OpenGL ES 3.1 の Java インターフェースは {@link android.opengl.GLES31} で提供されます。OpenGL ES 3.1 を使用する場合は、必ずマニフェスト ファイルで <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> タグと {@code android:glEsVersion} 属性を使用して宣言してください。次に例を示します。</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:glEsVersion="0x00030001" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<p>端末でサポートされている OpenGL ES のバージョンを実行時にチェックする方法など、OpenGL ES の使い方について詳しくは、<a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL ES API ガイド</a>をご覧ください。</p>
+
+<h3 id="AndroidExtensionPack">Android Extension Pack</h3>
+
+<p>OpenGL ES 3.1 に加えて、今回のリリースでは、高度なグラフィック機能のネイティブ サポートとそれに対応した Java インターフェースを実現する拡張パックが提供されています。これらの拡張機能は Android で 1 つのパッケージとして扱われます({@code ANDROID_extension_pack_es31a} 拡張機能が存在する場合、アプリではパッケージ内のすべての拡張機能が存在すると見なして、1 つの {@code #extension} ステートメントでシェーディング言語機能を有効にすることができます)。</p>
+
+<p>拡張パックは以下をサポートします。</p>
+
+<ul>
+<li>保証されたフラグメント シェーダによる、シェーダ保存バッファ、イメージ、アトミックのサポート(OpenGL ES 3.1 ではフラグメント シェーダのサポートはオプションです)</li>
+<li>テッセレーション シェーダとジオメトリ シェーダ</li>
+<li>ASTC(LDR)テクスチャ圧縮形式</li>
+<li>サンプル単位の補間とシェーディング</li>
+<li>フレーム バッファ内の各カラー アタッチメントに対応した各種のブレンドモード</li>
+</ul>
+
+<p>拡張パックの Java インターフェースは {@link android.opengl.GLES31Ext} で提供されます。アプリのマニフェストで、拡張パックをサポートしている端末にのみアプリをインストールする必要があることを宣言できます。次に例を示します。</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:name=“android.hardware.opengles.aep”
+ android:required="true" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<h2 id="Media">メディア</h2>
+
+<h3 id="Camera-v2">高度なカメラ機能に対応した Camera API</h3>
+
+<p>Android 5.0 では、写真のキャプチャや画像処理をきめ細かく行えるように、新しい <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">android.hardware.camera2</a> API が導入されています。プログラムから、{@link android.hardware.camera2.CameraManager#getCameraIdList() getCameraIdList()} を通じてシステムで使用できるカメラデバイスにアクセスし、{@link android.hardware.camera2.CameraManager#openCamera(java.lang.String, android.hardware.camera2.CameraDevice.StateCallback, android.os.Handler) openCamera()} を通じて特定のデバイスに接続できるようになりました。画像のキャプチャを開始するには、{@link android.hardware.camera2.CameraCaptureSession} を作成し、キャプチャした画像を送信するための {@link android.view.Surface} オブジェクトを指定します。{@link android.hardware.camera2.CameraCaptureSession} を設定して、1 枚のショットを撮影するようにしたり、一度に複数の画像を撮影するようにしたりできます。</p>
+
+<p>新しい画像がキャプチャされたときに通知を受けるには、{@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} リスナを実装してキャプチャ リクエストで設定します。画像キャプチャ リクエストが完了すると、{@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} リスナが {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback#onCaptureCompleted(android.hardware.camera2.CameraCaptureSession, android.hardware.camera2.CaptureRequest, android.hardware.camera2.TotalCaptureResult) onCaptureCompleted()} への呼び出しを受信し、{@link android.hardware.camera2.CaptureResult} に画像キャプチャ メタデータが設定されます。</p>
+
+<p>アプリで {@link android.hardware.camera2.CameraCharacteristics} クラスを使用すると、端末でどのカメラ機能が使用できるのかを検出できます。オブジェクトの {@link android.hardware.camera2.CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL INFO_SUPPORTED_HARDWARE_LEVEL} プロパティは、カメラの機能レベルを表します。</p>
+
+<ul>
+ <li>すべてのデバイスは少なくとも {@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY} のハードウェア レベルをサポートしています。このレベルは、非推奨となった {@link android.hardware.Camera} API のレベルにほぼ相当する機能を備えています。</li>
+ <li>{@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_FULL INFO_SUPPORTED_HARDWARE_LEVEL_FULL} のハードウェア レベルをサポートしているデバイスは、キャプチャとポストプロセスを手動でコントロールする機能と、高いフレームレートで高解像度画像をキャプチャする機能を備えています。</li>
+</ul>
+
+<p>最新の <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">Camera</a> API の使い方について詳しくは、このリリースに付属している {@code Camera2Basic} と {@code Camera2Video} の実装サンプルをご覧ください。</p>
+
+<h3 id="AudioPlayback">音声の再生</h3>
+<p>今回のリリースでは {@link android.media.AudioTrack} に次の変更が加えられています。</p>
+<ul>
+ <li>アプリから音声データを浮動小数点形式({@link android.media.AudioFormat#ENCODING_PCM_FLOAT ENCODING_PCM_FLOAT})で提供できるようになりました。これにより、ダイナミック レンジの向上、一貫性のある精度の向上、ヘッドルームの向上が可能になります。浮動小数点による計算は、特に中間計算の実行時に便利です。再生のエンドポイントでは、音声データに整数形式が使用され、ビット深度がより少なくなります(Android 5.0 では内部パイプラインの一部がまだ浮動小数点になっていません)。
+ <li>アプリから音声データを {@link java.nio.ByteBuffer} として、{@link android.media.MediaCodec} で提供されるものと同じ形式で提供できるようになりました。
+ <li>一部のアプリでは、{@link android.media.AudioTrack#WRITE_NON_BLOCKING WRITE_NON_BLOCKING} オプションを使用することでバッファ処理とマルチスレッド処理を簡素化できます。
+</ul>
+
+<h3 id="MediaPlaybackControl">メディア再生コントロール</h3>
+<p>メディアの再生についての情報をシステム UI に知らせ、アルバムアートの抽出と表示ができるように、新しい通知 / メディア API を使用してください。UI とサービスにまたがるメディアの再生のコントロールが、新しい {@link android.media.session.MediaSession} クラスと {@link android.media.session.MediaController} クラスを使用して、より簡単に行えるようになりました。</p>
+
+<p>新しい {@link android.media.session.MediaSession} クラスは非推奨となった {@link android.media.RemoteControlClient} クラスの代わりとなるもので、トランスポート コントロールとメディアボタンを処理するための単一のコールバック メソッド セットを提供します。アプリでメディアの再生を提供して Android <a href="{@docRoot}tv/index.html">TV</a> または <a href="{@docRoot}wear/index.html">Wear</a> プラットフォームで実行する場合は、{@link android.media.session.MediaSession} クラスを使用し、同じコールバック メソッドを通じてトランスポート コントロールを処理してください。</p>
+
+<p>新しい {@link android.media.session.MediaController} クラスを使用して独自のメディア コントローラ アプリを作成できるようになりました。このクラスは、アプリの UI プロセスからスレッドセーフな方法でメディアの再生を監視しコントロールするための手段を提供します。コントローラの作成時に {@link android.media.session.MediaSession.Token} オブジェクトを指定し、指定した {@link android.media.session.MediaSession} をアプリから操作できるようにします。{@link android.media.session.MediaController.TransportControls} のメソッドを使用すると、そのセッションで {@link android.media.session.MediaController.TransportControls#play() play()}、{@link android.media.session.MediaController.TransportControls#stop() stop()}、{@link android.media.session.MediaController.TransportControls#skipToNext() skipToNext()}、{@link android.media.session.MediaController.TransportControls#setRating(android.media.Rating) setRating()} などのコマンドを送信してメディアの再生をコントロールできます。また、コントローラで {@link android.media.session.MediaController.Callback} オブジェクトを登録し、そのセッションでメタデータや状態変更がないかをリッスンできます。</p>
+
+<p>さらに、新しい {@link android.app.Notification.MediaStyle} クラスを使用して、再生コントロールをメディア セッションに結び付けることができる高機能な通知を作成できます。</p>
+
+<h3 id="MediaBrowsing">メディアの参照</h3>
+<p>Android 5.0 では、新しい <a href="{@docRoot}reference/android/media/browse/package-summary.html">android.media.browse</a> API を通じて、あるアプリから別のアプリのメディア コンテンツ ライブラリを参照する機能が導入されています。アプリのメディア コンテンツを公開するには、{@link android.service.media.MediaBrowserService} クラスを拡張します。{@link android.service.media.MediaBrowserService} の実装で {@link android.media.session.MediaSession.Token} へのアクセスを提供することで、別のアプリがそのサービスを通じて提供されるメディア コンテンツを再生できるようになります。</p>
+<p>メディア ブラウザ サービスを操作するには、{@link android.media.browse.MediaBrowser} クラスを使用します。{@link android.media.browse.MediaBrowser} インスタンスの作成時に、{@link android.media.session.MediaSession} のコンポーネント名を指定します。その後、アプリからブラウザ インスタンスを使用して、関連付けられたサービスに接続し、{@link android.media.session.MediaSession.Token} オブジェクトを取得して、そのサービスを通じて公開されたコンテンツを再生できます。</p>
+
+<h2 id="Storage">ストレージ</h2>
+
+<h3 id="DirectorySelection">ディレクトリの選択</h3>
+
+<p>Android 5.0 では<a href="{@docRoot}guide/topics/providers/document-provider.html">ストレージ アクセス フレームワーク</a>が拡張され、ユーザーがディレクトリのサブツリー全体を選択し、それぞれのアイテムについてユーザーの確認を必要とせずに、含まれているすべてのドキュメントへの読み取り / 書き込みアクセス権をアプリに与えることができるようになります。</p>
+
+<p>ディレクトリのサブツリーを選択するには、{@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE OPEN_DOCUMENT_TREE} インテントを作成して送信します。サブツリーの選択をサポートしているすべての {@link android.provider.DocumentsProvider} インスタンスが表示され、ユーザーがディレクトリを参照して選択することができます。返される URI は、選択されたサブツリーへのアクセス手段を表します。その後、{@link android.provider.DocumentsContract#buildChildDocumentsUriUsingTree(android.net.Uri, java.lang.String) buildChildDocumentsUriUsingTree()} と {@link android.provider.DocumentsContract#buildDocumentUriUsingTree(android.net.Uri, java.lang.String) buildDocumentUriUsingTree()} を {@link android.content.ContentResolver#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String) query()} と一緒に使用することでサブツリーを探索できます。</p>
+
+<p>新しい {@link android.provider.DocumentsContract#createDocument(android.content.ContentResolver, android.net.Uri, java.lang.String, java.lang.String) createDocument()} メソッドを使用すると、サブツリーの配下に新しいドキュメントやディレクトリを作成できます。既存のドキュメントを管理するには、{@link android.provider.DocumentsContract#renameDocument(android.content.ContentResolver, android.net.Uri, java.lang.String) renameDocument()} と {@link android.provider.DocumentsProvider#deleteDocument(java.lang.String) deleteDocument()} を使用します。これらの呼び出しを実行する前に、{@link android.provider.DocumentsContract.Document#COLUMN_FLAGS COLUMN_FLAGS} をチェックして、提供側が呼び出しをサポートしているかどうかを確認してください。</p>
+
+<p>{@link android.provider.DocumentsProvider} を実装しようとしていて、サブツリーの選択をサポートしたい場合は、{@link android.provider.DocumentsProvider#isChildDocument(java.lang.String, java.lang.String) isChildDocument()} を実装し、{@link android.provider.DocumentsContract.Root#FLAG_SUPPORTS_IS_CHILD FLAG_SUPPORTS_IS_CHILD} を {@link android.provider.DocumentsContract.Root#COLUMN_FLAGS COLUMN_FLAGS} に追加します。</p>
+
+<p>Android 5.0 ではまた、共有ストレージ上の新しいパッケージ固有ディレクトリが導入されており、{@link android.provider.MediaStore} に含めることでアプリからメディア ファイルを配置することができます。新しい {@link android.content.Context#getExternalMediaDirs()} は、すべての共有ストレージ デバイスにあるこれらのディレクトリへのパスを返します。{@link android.content.Context#getExternalFilesDir(java.lang.String) getExternalFilesDir()} と同様に、アプリから追加の権限がなくても、返されるパスにアクセスできます。これらのディレクトリはプラットフォームによって定期的にスキャンされ、新しいメディアがないかが調べられますが、{@link android.media.MediaScannerConnection} を使用して明示的にスキャンし、新しいコンテンツがないかを調べることもできます。</p>
+
+<h2 id="Wireless">ワイヤレスと接続</h2>
+
+<h3 id="Multinetwork">マルチネットワーク接続</h3>
+<p>Android 5.0 では新しいマルチネットワーク API が導入されています。これらの API を通じてアプリで動的にスキャンを実行し、特定の機能を持つネットワークが使用できないかを調べて、それらへの接続を確立することができます。この機能は、アプリで SUPL、MMS、キャリア課金ネットワークなどの特殊なネットワークを必要とする場合や、特定のタイプのトランスポート コントロールを使用してデータを送信したい場合に便利です。</p>
+
+<p>アプリでネットワークを動的に選択して接続する手順は次のとおりです。</p>
+
+<ol>
+ <li>{@link android.net.ConnectivityManager} を作成します。</li>
+ <li>{@link android.net.NetworkRequest.Builder} クラスを使用して {@link android.net.NetworkRequest} オブジェクトを作成し、アプリで必要なネットワーク機能とトランスポート タイプを指定します。</li>
+<li>適切なネットワークがないかどうかをスキャンして調べるには、{@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} または {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()} を呼び出し、{@link android.net.NetworkRequest} オブジェクトと、{@link android.net.ConnectivityManager.NetworkCallback} の実装を渡します。検出した適切なネットワークに積極的に切り替えたい場合は、{@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} メソッドを使用します。スキャンしたネットワークに積極的に切り替えずに通知のみを受信するには、代わりに {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()} メソッドを使用します。</li>
+</ol>
+
+<p>適切なネットワークが検出されると、システムはそのネットワークに接続し、{@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()} コールバックを呼び出します。このコールバックの {@link android.net.Network} オブジェクトを使用して、ネットワークに関する詳細な情報を取得したり、選択されたネットワークを使用するようにトラフィックを設定したりできます。</p>
+
+<h3 id="BluetoothBroadcasting">Bluetooth Low Energy</h3>
+<p>Android 4.3 では、<a href="{@docRoot}guide/topics/connectivity/bluetooth-le.html">Bluetooth Low Energy</a>(<em>Bluetooth LE</em>)がプラットフォームでサポートされ、中央の役割として導入されました。Android 5.0 では、Android 搭載デバイスが Bluetooth LE の「周辺デバイス」<em></em>として機能できるようになりました。アプリからこの機能を使用することで、アプリの存在を付近のデバイスに知らせることができます。たとえば、デバイスを歩数計や健康管理機器として機能させるアプリを作成して、それらのデータを他の Bluetooth LE 対応デバイスとやり取りすることができます。</p>
+<p>新しい {@link android.bluetooth.le} API を使用すると、アプリからアドバタイズをブロードキャストしたり、応答の有無をスキャンして調べたり、付近の Bluetooth LE 対応デバイスとの接続を確立したりできます。新しいアドバタイズ機能やスキャン機能を使用するには、{@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN} 権限をマニフェストに追加します。ユーザーは、Play ストアでアプリを更新またはダウンロードするときに、「Bluetooth接続情報: Bluetoothの制御(付近のBluetoothデバイスへの送信、詳細情報の取得など)をアプリに許可します」という権限をアプリに許可するかどうかたずねられます。</p>
+
+<p>他のデバイスがアプリを検出できるように Bluetooth LE によるアドバタイズを開始するには、{@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()} を呼び出し、{@link android.bluetooth.le.AdvertiseCallback} クラスの実装を渡します。このコールバック オブジェクトは、アドバタイズ操作の成否を知らせる通知を受信します。</p>
+
+<p> Android 5.0 で導入された {@link android.bluetooth.le.ScanFilter} クラスをアプリで使用すると、必要な特定のタイプのデバイスのみを探すスキャンを実行できます。Bluetooth LE デバイスを探すためのスキャンを開始するには、{@link android.bluetooth.le.BluetoothLeScanner#startScan(android.bluetooth.le.ScanCallback) startScan()} を呼び出し、フィルタのリストを渡します。このメソッド呼び出しでは、{@link android.bluetooth.le.ScanCallback} の実装を渡し、Bluetooth LE のアドバタイズが検出されたときにそれを知らせるようにする必要もあります。 </p>
+
+<h3 id="NFCEnhancements">NFC の機能強化</h3>
+<p>Android 5.0 では、NFC をより幅広く柔軟に利用できるように、次の機能強化が追加されています。</p>
+
+<ul>
+<li>Android Beam が「共有」<em></em>メニューで使用できるようになりました。</li>
+<li>ユーザーの端末でアプリから Android Beam を起動し、{@link android.nfc.NfcAdapter#invokeBeam(android.app.Activity) invokeBeam()} を呼び出してデータを共有することができます。これにより、ユーザーが手動で端末をタップして別の NFC 対応端末へのデータ転送を実行する必要がなくなります。</li>
+<li>新しい {@link android.nfc.NdefRecord#createTextRecord(java.lang.String, java.lang.String) createTextRecord()} メソッドを使用して、UTF-8 テキストデータを含む NDEF レコードを作成できます。</li>
+<li>支払い機能を備えるアプリを開発している場合、<code><a href="{@docRoot}reference/android/nfc/cardemulation/CardEmulation.html#registerAidsForService(android.content.ComponentName, java.lang.String, java.util.List<java.lang.String>)">registerAidsForService()</a></code> を呼び出して NFC アプリケーション ID(AID)を動的に登録できるようになりました。また、{@link android.nfc.cardemulation.CardEmulation#setPreferredService(android.app.Activity, android.content.ComponentName) setPreferredService()} を使用して、特定のアクティビティがフォアグラウンドに存在するときに使用する優先のカード エミュレーション サービスを設定できます。</li>
+</ul>
+
+<h2 id="Power">Project Volta</h2>
+
+<p>新機能に加えて、Android 5.0 では特に電池寿命が向上しています。新しい API やツールを使用して、アプリの消費電力に関する情報の取得や消費電力の最適化を行ってください。</p>
+
+<h3 id="JobScheduler">ジョブのスケジューリング</h3>
+<p>Android 5.0 で提供される新しい {@link android.app.job.JobScheduler} API を使用すると、システムが後で、または指定の条件(端末の充電時など)の下で、非同期に実行するジョブを定義することによって、電池寿命を最適化できます。ジョブ スケジューリングは、アプリで次のような状況を処理する場合に便利です。</p>
+<ul>
+ <li>現在ユーザーが関与していない作業の実行を遅らせることができる場合。</li>
+ <li>実行を遅らせた作業を、ユニットが電源に接続されたときに実行する場合。</li>
+ <li>ネットワーク アクセスや Wi-Fi 接続を必要とするタスクがある場合。</li>
+ <li>定期的なスケジュールで一括して実行したいタスクが複数ある場合。</li>
+
+</ul>
+
+<p>作業ユニットは {@link android.app.job.JobInfo} オブジェクトによってカプセル化されます。このオブジェクトでスケジューリング条件を指定します。</p>
+
+<p>スケジューリング済みのタスクをどのように実行するのかを設定するには、{@link android.app.job.JobInfo.Builder} クラスを使用します。タスクが次のような特定の条件下で実行されるようにスケジューリングできます。</p>
+
+<ul>
+ <li>端末の充電時に開始する</li>
+ <li>端末が定額制ネットワークに接続されたときに開始する</li>
+ <li>端末がアイドル状態のときに開始する</li>
+ <li>特定の期限が過ぎる前に完了する、または最小限の遅延で完了する</li>
+</ul>
+
+<p>たとえば、次のようなコードを追加すると、タスクを定額制ネットワーク上で実行できます。</p>
+
+<pre>
+JobInfo uploadTask = new JobInfo.Builder(mJobId,
+ mServiceComponent /* JobService component */)
+ .setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED)
+ .build();
+JobScheduler jobScheduler =
+ (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
+jobScheduler.schedule(uploadTask);
+</pre>
+
+<p>端末の電力が安定している場合(つまり、端末が 2 分以上電源に接続されていて、電池が<a href="{@docRoot}reference/android/content/Intent.html#ACTION_BATTERY_OKAY">正常レベル</a>にある場合)には、ジョブがまだ期限切れになっていなくても、実行の準備ができているスケジューリング済みのジョブがすべて実行されます。</p>
+
+<p>{@link android.app.job.JobScheduler} API の使用例については、このリリースに付属している {@code JobSchedulerSample} の実装サンプルをご覧ください。</p>
+
+<h3 id="PowerMeasurementTools">電池の使用統計情報を提供するデベロッパー向けツール</h3>
+
+<p>新しい {@code dumpsys batterystats} コマンドでは、端末での電池の使用に関して役立つ統計データが、一意のユーザー ID(UID)別に整理されて生成されます。次のような統計情報が生成されます。</p>
+
+<ul>
+<li>電池関連のイベントの履歴
+<li>端末の全体的な統計情報
+<li>UID 別やシステム コンポーネント別の推定電力使用量
+<li>アプリ別のパケットあたりのモバイル ミリ秒
+<li>システム UID 別に集計される統計情報
+<li>アプリ UID 別に集計される統計情報
+</ul>
+
+<p>出力をカスタマイズするための各種オプションについて調べるには、{@code --help} オプションを使用します。たとえば対象のアプリ パッケージについて、端末が最後に充電されてから現在までの電池の使用統計情報を出力するには、次のコマンドを実行します。
+<pre>
+$ adb shell dumpsys batterystats --charged &lt;package-name&gt;
+</pre>
+
+<p>{@code dumpsys} コマンドの出力に対して<a href="https://github.com/google/battery-historian" class="external-link">電池履歴</a>ツールを使用すると、電力に関するイベントをログから取得して視覚的に表現する HTML を生成できます。これらの情報を利用することで、電池に関連した問題の把握や診断がしやすくなります。</p>
+
+<h2 id="Enterprise">職場向けや教育向けの Android</h2>
+<h3 id="ManagedProvisioning">管理対象プロビジョニング</h3>
+
+<p>Android 5.0 では社内環境の中でアプリを実行するための新機能が提供されています。<a href="{@docRoot}guide/topics/admin/device-admin.html">端末管理者</a>は、ユーザーが既存の個人用アカウントを持っている場合に、管理対象プロビジョニングのプロセスを開始して、同時かつ別々に存在する「管理対象プロフィール」<em></em>を端末に追加することができます。管理対象プロフィールに関連付けられたアプリは、管理対象外のアプリと一緒に、ユーザーのランチャー、最近使ったアプリ画面、通知に表示されます。</p>
+
+<p>管理対象プロビジョニングのプロセスを開始するには、{@link android.content.Intent} で {@link android.app.admin.DevicePolicyManager#ACTION_PROVISION_MANAGED_PROFILE ACTION_PROVISION_MANAGED_PROFILE} を送信します。呼び出しが成功すると、システムから {@link android.app.admin.DeviceAdminReceiver#onProfileProvisioningComplete(android.content.Context, android.content.Intent) onProfileProvisioningComplete()} コールバックが起動されます。その後、{@link android.app.admin.DevicePolicyManager#setProfileEnabled(android.content.ComponentName) setProfileEnabled()} を呼び出してこの管理対象プロフィールを有効にすることができます。</p>
+
+<p>デフォルトでは、一部の少数のアプリのみが管理対象プロフィールで有効になります。管理対象プロフィールで追加のアプリをインストールするには、{@link android.app.admin.DevicePolicyManager#enableSystemApp(android.content.ComponentName, android.content.Intent) enableSystemApp()} を呼び出します。</p>
+
+<p>ランチャー アプリを開発している場合は、新しい {@link android.content.pm.LauncherApps} クラスを使用して、現在のユーザーの起動可能なアクティビティのリストや、関連するすべての管理対象プロフィールを取得できます。ランチャーでアイコン drawable に作業バッジを付けると、管理対象アプリを視覚的に目立たせることができます。バッジ付きのアイコンを取得するには {@link android.content.pm.PackageManager#getUserBadgedIcon(android.graphics.drawable.Drawable, android.os.UserHandle) getUserBadgedIcon()} を呼び出します。</p>
+
+<p>新機能の使い方については、このリリースに付属している {@code BasicManagedProfile} の実装サンプルをご覧ください。</p>
+
+<h3 id="DeviceOwner">端末所有者</h3>
+<p>Android 5.0 では、端末所有者アプリの展開機能が導入されています。<em></em>「端末所有者」は特殊なタイプの<a href="{@docRoot}guide/topics/admin/device-admin.html">端末管理者</a>で、第 2 ユーザーの作成や削除、端末全体の設定について、さらに詳細な操作を実行できます。端末管理者アプリでは {@link android.app.admin.DevicePolicyManager} クラスのメソッドを使用して、管理対象端末の設定、セキュリティ、アプリをきめ細かくコントロールできます。端末で有効にできる端末管理者は一度に 1 つだけです。</p>
+
+<p>端末管理者を展開して有効にするには、端末がプロビジョニングされていない状態となっている間に、プログラミング アプリから端末への NFC データ転送を実行する必要があります。このデータ転送では、<a href="#ManagedProvisioning">管理対象プロビジョニング</a>で説明しているインテントのプロビジョニングの場合と同じ情報が送信されます。</p>
+
+<h3 id="ScreenPinning">画面の固定</h3>
+
+<p>Android 5.0 では、新しい画面固定 API が導入されています。これを使用すると、ユーザーがタスクから離れる操作や通知による割り込みを一時的に制限することができます。たとえば Android で、重要度の高い評価要件に対応した教育向けアプリや、単一用途のアプリ、またはキオスクアプリを開発している場合などに役立ちます。アプリで画面の固定を有効にすると、そのモードを終了するまで、ユーザーは通知を表示することも、他のアプリにアクセスすることも、ホーム画面に戻ることもできなくなります。</p>
+
+<p>次の 2 つの方法で画面の固定を有効にすることができます。</p>
+
+<ul>
+<li><strong>手動による方法:</strong> ユーザーは [設定] &gt; [セキュリティ] &gt; [画面の固定]<em></em> で画面の固定を有効にすることができ、最近使ったアプリ画面に表示される緑色のピンアイコンをタップすることで、固定したいタスクを選択できます。</li> <li><strong>プログラミングによる方法:</strong> プログラムから画面の固定を有効にするには、アプリで {@link android.app.Activity#startLockTask() startLockTask()} を呼び出します。リクエストする側のアプリが端末所有者でない場合は、確認のメッセージがユーザーに表示されます。端末所有者アプリから {@link android.app.admin.DevicePolicyManager#setLockTaskPackages(android.content.ComponentName, java.lang.String[]) setLockTaskPackages()} メソッドを呼び出すと、ユーザーの確認手順なしでアプリの固定を有効にすることができます。</li>
+</ul>
+
+<p>タスクのロックが有効になると、次のような動作になります。</p>
+
+<ul>
+<li>ステータスバーが空になり、ユーザーの通知やステータス情報が表示されません。</li>
+<li>ホームボタンと最近使ったアプリボタンが表示されません。</li>
+<li>他のアプリから新しいアクティビティを起動できません。</li>
+<li>現在のアプリからは、新しいタスクが作成されない限り、新しいアクティビティを起動できます。</li>
+<li>画面の固定が端末所有者によって開始されている場合は、アプリから {@link android.app.Activity#stopLockTask() stopLockTask()} を呼び出すまで、ユーザーは引き続きアプリにロックされます。</li>
+<li>画面の固定が端末所有者でない別のアプリによって、またはユーザーによって直接、有効にされている場合には、ユーザーは戻るボタンと最近使ったアプリボタンを同時に押すことで画面の固定を終了できます。</li>
+
+</ul>
+
+<h2 id="Printing">印刷フレームワーク</h2>
+
+<h3 id="PDFRender">PDF をビットマップとしてレンダリング</h3>
+<p>新しい {@link android.graphics.pdf.PdfRenderer} クラスを使用して、PDF ドキュメントのページを印刷用のビットマップ画像にレンダリングできるようになりました。印刷可能なコンテンツの書き込み先となる、シーク可能な(つまり、コンテンツへのランダム アクセスが可能な){@link android.os.ParcelFileDescriptor} を指定する必要があります。アプリでは、{@link android.graphics.pdf.PdfRenderer#openPage(int) openPage()} でレンダリング用のページを取得した後、{@link android.graphics.pdf.PdfRenderer.Page#render(android.graphics.Bitmap, android.graphics.Rect, android.graphics.Matrix, int) render()} を呼び出して、開いている {@link android.graphics.pdf.PdfRenderer.Page} をビットマップに変換できます。また、ドキュメントの一部分だけをビットマップ画像に変換したい場合は追加のパラメータを設定できます(たとえば、ドキュメントを拡大するために<a href="http://en.wikipedia.org/wiki/Tiled_rendering" class="external-link">タイル レンダリング</a>を実装する場合など)。</p>
+
+<p>新しいアプリの使用例については、{@code PdfRendererBasic} のサンプルをご覧ください。</p>
+
+<h2 id="System">システム</h2>
+<h3 id="AppUsageStatistics">アプリの使用統計情報</h3>
+<p>新しい {@link android.app.usage} API を使用して Android 端末のアプリ使用履歴にアクセスできるようになりました。この API では、非推奨となった {@link android.app.ActivityManager#getRecentTasks(int, int) getRecentTasks()} メソッドよりも詳細な使用統計情報が提供されます。この API を使用するには、最初にマニフェストで {@code "android.permission.PACKAGE_USAGE_STATS"} 権限を宣言する必要があります。また、ユーザーも [設定] &gt; [セキュリティ] &gt; [アプリ]<em></em> を通じてこのアプリの使用アクセス権を有効にする必要があります。</p>
+
+<p>使用統計データはアプリ単位で収集され、毎日、毎週、毎月、毎年の各期間でデータが集計されます。データの最長保持期間は次のとおりです。</p>
+
+<ul>
+ <li>毎日のデータ: 7 日間</li>
+ <li>毎週のデータ: 4 週間</li>
+ <li>毎月のデータ: 6 か月</li>
+ <li>毎年のデータ: 2 年</li>
+</ul>
+
+<p>各アプリについて次のデータが記録されます。</p>
+<ul>
+<li>アプリが最後に使用された時間</li>
+<li>対象期間(1 日、1 週間、1 か月、または 1 年)にアプリがフォアグラウンドに存在した合計時間</li>
+<li>1 日の間にコンポーネント(パッケージとアクティビティ名により識別される)がフォアグラウンドからバックグラウンドに移動したときに取得されるタイムスタンプ</li>
+<li>端末の設定が変更されたとき(回転の結果端末の向きが変化したときなど)に取得されるタイムスタンプ</li>
+</ul>
+
+<h2 id="TestingA11y">テストとユーザー補助 </h2>
+
+<h3 id="TestingA11yImprovements">テストとユーザー補助の向上</h3>
+<p>Android 5.0 ではテストとユーザー補助に関する次のサポートが追加されています。</p>
+
+<ul>
+<li>新しい {@link android.app.UiAutomation#getWindowAnimationFrameStats() getWindowAnimationFrameStats()} メソッドと {@link android.app.UiAutomation#getWindowContentFrameStats(int) getWindowContentFrameStats()} メソッドは、ウィンドウのアニメーションとコンテンツに関するフレーム統計情報を取得します。これらのメソッドを使用して計測テストを記述すれば、アプリがスムーズなユーザー エクスペリエンスを提供するのに十分な更新頻度でフレームを描画しているかどうかを評価できます。</li>
+
+<li>新しい {@link android.app.UiAutomation#executeShellCommand(java.lang.String) executeShellCommand()} メソッドを使用すると、計測テストからシェルコマンドを実行できます。コマンドの実行は端末に接続されたホストから {@code adb shell} を実行するのと同様に行え、{@code dumpsys}、{@code am}、{@code content}、{@code pm} などのシェルベースのツールを使用できます。</li>
+
+<li>ユーザー補助 API(<a href="{@docRoot}tools/help/uiautomator/index.html">{@code UiAutomator}</a> など)を使用するユーザー補助のサービスやテストツールで、視覚に障がいのないユーザーが操作できる画面上のウィンドウについて、そのプロパティに関する詳細情報を取得できるようになりました。{@link android.view.accessibility.AccessibilityWindowInfo} オブジェクトのリストを取得するには、新しい {@link android.accessibilityservice.AccessibilityService#getWindows() getWindows()} メソッドを呼び出します。</li>
+
+<li>新しい {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} クラスを使用すると、{@link android.view.accessibility.AccessibilityNodeInfo} で実行する標準の操作やカスタマイズされた操作を定義できます。新しい {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} クラスは、従来 {@link android.view.accessibility.AccessibilityNodeInfo} に存在した操作関連の API の代わりとなるものです。</li>
+
+<li>Android 5.0 では、音声合成をよりきめ細かくアプリでコントロールできます。アプリで新しい {@link android.speech.tts.Voice} クラスを使用すると、特定の言語、音質、レイテンシ速度に関連付けられた音声プロフィールや、音声合成エンジン固有のパラメータを使用できます。</li>
+</ul>
+
+<h2 id="IME">IME</h2>
+
+<h3 id="Switching">入力言語の切り替えやすさの向上</h3>
+
+<p>Android 5.0 以降、ユーザーはプラットフォームでサポートされているすべての<a href="{@docRoot}guide/topics/text/creating-input-method.html">インプット メソッド エディタ(IME)</a>を簡単に切り替えられるようになります。指定された切り替え操作(通常はソフト キーボード上の地球アイコンのタップ)を行うと、それらの IME のすべてが循環して切り替わります。この動作変更は {@link android.view.inputmethod.InputMethodManager#shouldOfferSwitchingToNextInputMethod(android.os.IBinder) shouldOfferSwitchingToNextInputMethod()} メソッドによって実装されます。</p>
+
+<p>また、次の IME に切り替え機能が組み込まれているかどうか(つまり、対象の IME が次に続く IME への切り替えをサポートしているかどうか)がチェックされるようになりました。切り替え機能のある IME から切り替え機能のない IME への循環切り替えは行われません。この動作変更は {@link android.view.inputmethod.InputMethodManager#switchToNextInputMethod(android.os.IBinder, boolean) switchToNextInputMethod()} メソッドによって実装されます。
+
+<p>最新の IME 切り替え API の使用例については、このリリースに付属している最新のソフト キーボードの実装サンプルをご覧ください。IME の切り替えを実装する方法について詳しくは、<a href="{@docRoot}guide/topics/text/creating-input-method.html">入力方法の作成</a>をご覧ください。
+</p>
+
+<h2 id="Manifest">マニフェスト宣言</h2>
+
+<h3 id="ManifestFeatures">宣言可能な必須機能</h3>
+<p>次の値が <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> 要素でサポートされるようになりました。これにより、アプリで必要としている機能を備えている端末にのみアプリをインストールできるようになります。</p>
+
+<ul>
+<li>{@link android.content.pm.PackageManager#FEATURE_AUDIO_OUTPUT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_POST_PROCESSING}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_SENSOR}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_RAW}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_LEVEL_FULL}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_GAMEPAD}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LIVE_TV}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_MANAGED_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LEANBACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_OPENGLES_EXTENSION_PACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SECURELY_REMOVES_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_AMBIENT_TEMPERATURE}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_HEART_RATE_ECG}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_RELATIVE_HUMIDITY}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_VERIFIED_BOOT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_WEBVIEW}</li>
+</ul>
+
+<h3 id="Permissions">ユーザー権限</h3>
+
+<p>次の権限が <a href="{@docRoot}guide/topics/manifest/uses-permission-element.html">{@code <uses-permission>}</a> 要素でサポートされ、アプリで特定の API へのアクセスに必要な権限を宣言できるようになりました。</p>
+
+<ul>
+<li>{@link android.Manifest.permission#BIND_DREAM_SERVICE}: API レベル 21 以降を対象とする場合は、システムによるバインドのみが可能となるようにするため、<a href="{@docRoot}about/versions/android-4.2.html#Daydream">Daydream</a> サービスでこの権限が必要になります。</li>
+</ul>
diff --git a/docs/html-intl/intl/ja/about/versions/lollipop.jd b/docs/html-intl/intl/ja/about/versions/lollipop.jd
new file mode 100644
index 0000000..9c7c52c
--- /dev/null
+++ b/docs/html-intl/intl/ja/about/versions/lollipop.jd
@@ -0,0 +1,256 @@
+page.title=Android Lollipop
+
+@jd:body
+
+
+
+
+
+
+
+
+
+
+ <div style="padding:0px 0px 0px 20px;float:right;margin:0 -10px 0 0">
+ <img src="{@docRoot}images/home/l-hero_2x.png" srcset="{@docRoot}images/home/l-hero.png 1x, {@docRoot}images/home/l-hero_2x.png 2x" width="460" height="300" >
+ </div>
+
+ <div class="landing-docs" style="float:right;clear:both;margin:68px 0 2em 3em;">
+ <div class="col-4 normal-links highlights" style="font-size:12px;">
+ <h3 id="thisd" >主なデベロッパー機能</h3>
+ <ul style="list-style-type:none;">
+ <li><a href="#Material">Material Design</a></li>
+ <li><a href="#Perf">パフォーマンス重視</a></li>
+ <li><a href="#Notifications">通知</a></li>
+ <li><a href="#TV">アプリを大画面で</a></li>
+ <li><a href="#Documents">アプリのドキュメント化</a></li>
+ <li><a href="#Connectivity">進化した接続性</a></li>
+ <li><a href="#Graphics">高性能グラフィックス</a></li>
+ <li><a href="#Audio">さらに強化された音声</a></li>
+ <li><a href="#Camera">カメラと動画の拡張</a></li>
+ <li><a href="#Work">職場での Android</a></li>
+ <li><a href="#ScreenCapture">画面のキャプチャと共有</a></li>
+ <li><a href="#Sensors">新しいタイプのセンサー</a></li>
+ <li><a href="#WebView">Chromium WebView</a></li>
+ <li><a href="#Accessibility">ユーザー補助機能と入力</a></li>
+ <li><a href="#Battery">省電力アプリ用のツール</a></li>
+ </ul>
+ </div>
+</div>
+
+
+
+
+
+
+
+<p>Android 5.0 Lollipop は、これまでの Android の中で最も大きく刷新された意欲的なリリースです。</p>
+
+<p>このリリースには、ユーザー向けの新しい機能だけでなく、デベロッパー向けに数多くの API が追加されています。これらの API を使用することで、携帯電話、タブレット、ウェアラブルに加え、テレビや自動車用にも Android を拡張できます。</p>
+
+<p>新しいデベロッパー向け API の概要については、<a href="{@docRoot}about/versions/android-5.0.html">Android 5.0 API</a> をご覧ください。Android 5.0 のユーザー向けの新機能については <a href="http://www.android.com/versions/lollipop-5-0/">www.android.com</a> をご覧ください。</p>
+
+
+
+<h2 id="Material">Material Design</h2>
+
+<p>Android 5.0 では新たに <a href="http://www.google.com/design/spec">Material Design</a> が導入され、拡張 UI ツールキットを使用することで新しいデザイン パターンをアプリに簡単に統合できるようになりました。 </p>
+
+
+
+<p>新しい <strong>3D ビュー</strong>機能では、z レベルを設定することでビュー階層から要素を持ち上げることができるようになりました。また、<strong>リアルタイム シャドウ</strong>機能により、要素が移動しても影を追随させることができます。</p>
+
+
+<p><strong>アクティビティ遷移</strong>機能が組み込まれたことで、美しいアニメーションを使って次の状態へスムーズに遷移できるようになりました。マテリアル テーマを使用すると、アクティビティの遷移がさらにスムーズになります。たとえば、アクティビティ間で<strong>共有視覚要素</strong>を使用できるようになりました。</p>
+
+
+
+<div style="width:290px;margin-right:35px;float:left">
+ <div class="framed-nexus5-port-span-5">
+ <video class="play-on-hover" autoplay="">
+ <source src="/design/material/videos/ContactsAnim.mp4">
+ <source src="/design/videos/ContactsAnim.webm">
+ <source src="/design/videos/ContactsAnim.ogv">
+ </video>
+ </div>
+ <div style="font-size:10pt;margin-left:20px;margin-bottom:30px">
+ <em></em>端末画面をクリックすると動作が再現されます
+ </div>
+</div>
+
+
+<p>アプリ内のタップ コントロール(ボタン、チェックボックスなど)にリップル アニメーションを適用できます。
+
+<p>XML でベクター ドローアブルを定義して、さまざまな方法でアニメーション化することも可能です。ベクター ドローアブルは定義を変更することなく拡大縮小できるため、単色のアプリ内アイコンに最適です。</p>
+
+<p>システム管理の処理スレッドとして <strong>RenderThread</strong> が追加されており、メインの UI スレッドに遅延が発生してもアニメーションをスムーズに再生できます。 </p>
+
+
+<h2 id="Perf">パフォーマンス重視</h2>
+
+<p>Android 5.0 では、より高速でスムーズな演算処理が実現します。</p>
+
+<p>新しい <strong>ART ランタイム</strong>に完全に移行しました。ART は基礎から徹底的に再構築したランタイムで、AOT(ahead-of-time)、JIT(just-in-time)、インタプリタ型のコードをまとめて処理できます。ARM、x86、MIPS アーキテクチャに対応した 64 ビット完全互換のランタイムです。</p>
+
+<p>ART は、アプリのパフォーマンスと応答性を改善します。ガベージ コレクションを効率的することで、GC イベントによる一時停止の回数や時間を減らしました。垂直同期の期間にうまく適合するようになったことで、アプリがフレームをスキップすることもなくなります。また、メモリを動的に移動してフォアグラウンドのパフォーマンスも最適化しています。 </p>
+
+<p>Android 5.0 では、Nexus 9 の NVIDIA Tegra K1 で採用されている<strong>64 ビット アーキテクチャ</strong>のプラットフォーム サポートを導入しています。最適化によって広いアドレス空間が提供され、特定の演算負荷の処理能力が向上しました。Java で記述されているアプリは、修正なしで自動的に 64 ビット アプリとして実行されます。ネイティブ コードを使用するアプリのためには、ARM v8、x86-64、MIPS-64 用の新しい ABI をサポートするため NDK を拡張しました。</p>
+
+<p>Android 5.0 では、パフォーマンスをさらに向上させるため、A/V 同期についても改善に取り組みました。音声と映像のパイプラインを搭載したことでタイムスタンプの正確性が向上し、動画アプリやゲームのコンテンツの同期がスムーズに行われるようになりました。</p>
+
+
+<h2 id="Notifications">通知</h2>
+
+<p>Android 5.0 の通知は、より見やすく、アクセスしやすく、カスタマイズしやすくなりました。 </p>
+
+<img src="{@docRoot}images/versions/notification-headsup.png" style="float:right; margin:0 0 40px 60px" width="300" height="224" />
+
+<p>さまざまな通知の詳細を<strong>ロック画面</strong>に表示できるようになり、通知内容をすべて表示するか、一部だけ表示するか、表示しないかをユーザーが選択できます。 </p>
+
+<p>着信などの重要な通知は<strong>警告通知</strong>と呼ばれるフローティング ウィンドウに表示されるため、使用中のアプリを表示したまま応答したり破棄したりできます。</p>
+
+<p>Android 5.0 では、通知に<strong>新しいメタデータ</strong>を追加して、関連付けられている連絡先(ランク付け用)、カテゴリ、優先度を収集できるようになりました。</p>
+
+<p>新たに追加されたメディア通知テンプレートを使用すると、最大 6 つの操作ボタンを使用して、一貫性のあるメディア コントロール(例: 「いいね」や「+1」)を通知に追加できます。RemoteViews はもう必要ありません。</p>
+
+
+
+<h2 id="TV">アプリを大画面で</h2>
+
+<p><a href="http://developer.android.com/tv/index.html">Android TV</a> は、アプリを大画面で楽しむためのテレビ用プラットフォームを提供します。シンプルなホーム画面をベースに構成されており、ユーザーへのおすすめや音声検索によってコンテンツを簡単に見つけることができます。</p>
+
+<p>Android TV なら、アプリやゲームを<strong>迫力の大画面</strong>で楽しむことができ、ゲーム コントローラなどの入力デバイスにも対応しています。Android では <a href="{@docRoot}tools/support-library/features.html#v17-leanback">v17 サポート ライブラリ</a>に <strong>Leanback UI フレームワーク</strong>が用意されており、離れた場所からでも操作しやすい 10 フィート UI を簡単に実現できます。</p>
+
+<p><strong>Android TV Input Framework</strong>(TIF)を使用すると、HDMI 入力、テレビチューナー、IPTV 対応受信機などからの動画ストリームを TV アプリで処理できます。TV Input が公開しているメタデータを使用することで、放送中のテレビ番組を検索できるようにしたり、ユーザーへのおすすめを表示したりできます。また、HDMI-CEC コントロール サービスを使用して、複数のデバイスを 1 つのリモコンで操作できるようにすることも可能です。 </p>
+
+<p>TV Input フレームワークを使用すると、さまざまな入力ソースからのテレビ番組をまとめ、ユーザーが 1 つのインターフェースで閲覧したり視聴したりできるようにすることができます。提供するコンテンツの TV Input サービスを作成することで、ユーザーが TV デバイスでコンテンツを視聴する可能性を高めることができます。</p>
+
+
+
+<img src="{@docRoot}images/versions/recents_screen_2x.png" srcset="{@docRoot}images/versions/recents_screen.png 1x, {@docRoot}images/versions/recents_screen_2x.png 2x" style="float:right; margin:0 0 40px 60px" width="300" height="521" />
+
+<h2 id="Documents">アプリのドキュメント化</h2>
+
+<p>Android 5.0 では、[概要](以前は [最近])のスペースをデザインしなおして用途を広げ、マルチタスクにも使えるようにしました。</p>
+
+<p>新しい API を使用することで、アプリ内の各アクティビティを個別のドキュメントとして、他の最近の画面と並べて表示できます。</p>
+
+<p>これにより、ユーザーがコンテンツやサービスにすばやくアクセスできるようになります。たとえば、生産性アプリのファイル、ゲームでのプレーヤーの組み合わせ、メッセージ アプリのチャットなどを、別々のドキュメントにして同時に表示できます。 </p>
+
+
+
+<h2 id="Connectivity">進化した接続性</h2>
+
+<p>Android 5.0 に追加された新しい API を使用すると、アプリと <strong>BLE</strong>(Bluetooth Low Energy)の同時処理が可能になり、スキャン(セントラル モード)とアドバタイズ(ペリフェラル モード)の両方を行うことができます。</p>
+
+<p>新しい<strong>マルチネットワーキング</strong>機能により、アプリから特定の機能を利用できるネットワーク(Wi-Fi、モバイル、従量制、特定のネットワーク機能を提供するネットワークなど)を探せるようになりました。ネットワークが見つかったら、アプリから接続を要求したり、切断やネットワーク変更に対して応答したりできます。</p>
+
+<p><strong>NFC</strong> API では、アプリから NFC AID(Application ID)を動的に登録できるようになりました。また、アクティブなサービスごとに望ましいカード エミュレーション サービスを設定したり、UTF-8 テキストデータを格納する NDEF レコードを作成したりすることも可能になりました。</p>
+
+
+
+<h2 id="Graphics">高性能グラフィックス</h2>
+
+<p><strong><a href="http://www.khronos.org/opengles/3_X/">Khronos OpenGL ES 3.1</a></strong> をサポートしたことで、対応デバイスで実行するゲームやアプリに高性能な 2D / 3D グラフィックス機能を利用できるようになりました。 </p>
+
+<p>OpenGL ES 3.1 により、コンピュート シェーダー、ステンシル テクスチャ、アクセラレータによる視覚効果、高品質 ETC2/EAC テクスチャ圧縮、高度なテクスチャ レンダリング、標準化されたテクスチャ サイズ、レンダー バッファ フォーマットなど、さまざまな機能が追加されました。</p>
+
+
+<div class="figure" style="width:350px; margin:0 0 0 60px">
+<img src="{@docRoot}images/versions/rivalknights.png" style="float:right;" width="350" height="525" />
+<p class="img-caption">Gameloft の Rival Knights では、AEP の ASTC(Adaptive Scalable Texture Compression)と ES 3.1 のコンピュート シェーダーを使用して、ハイ ダイナミック レンジ(HDR)によるブルーム効果や詳細なグラフィックスを実現しています。</p>
+</div>
+
+<p>Android 5.0 には OpenGL ES 拡張をまとめた <strong>Android Extension Pack</strong>(AEP)も追加されており、テッセレーション シェーダー、ジオメトリ シェーダー、ASTC テクスチャ圧縮、サンプル単位での補間とシェーディングなど、高度なレンダリング機能を使用できます。AEP を使用することで、GPU を無駄なく利用して高性能なグラフィックスを実現できます。</p>
+
+
+<h2 id="Audio">さらに強化された音声</h2>
+
+<p>新しい音声キャプチャ デザインにより、<strong>音声入力の待ち時間が短縮</strong>されました。新しいデザインには、ブロックが読み込み中にしか発生しない高速キャプチャ スレッド、ネイティブ サンプル レートでの高速トラック キャプチャ クライアント、チャンネル カウント、ビット深度、リサンプリングを提供する通常のキャプチャ クライアント、チャンネルのアップミックスとダウンミックス、ビット深度の調整などが含まれています。</p>
+
+<p>マルチチャンネルの<strong>音声ストリーム ミキシング</strong>を使うと、5.1 や 7.1 を含め最大 8 つのチャンネルをミキシングできる本格的なオーディオ アプリを実現できます。</p>
+
+<p>アプリでは、メディア コンテンツを公開したり、他のアプリが公開している<strong>メディアを閲覧</strong>したり、その再生をリクエストしたりできます。コンテンツはクエリ可能なインターフェースで公開されるため、端末に保持する必要はありません。</p>
+
+<p>また、特定のロケール、音質、レイテンシ速度に関連付けられた音声プロフィールを使うことで、<strong>合成音声によるテキスト読み上げ</strong>をきめ細かくコントロールできます。新しい API では、合成エラーチェック、ネットワーク合成、言語検出、ネットワーク フォールバックなどへの対応も進めました。</p>
+
+<p>Android が標準の <strong>USB オーディオ</strong>機器にも対応したことで、USB ヘッドセット、スピーカー、マイクなどの高性能デジタル機器も使用できるようになりました。Android 5.0 には、<strong>Opus</strong> 音声コーデックのサポートも追加されています。</p>
+
+<p>メディア再生をコントロールするための新しい <strong>{@link android.media.session.MediaSession}</strong> API を使用することで、複数の画面にわたって一貫性のあるメディア コントロールや各種コントローラを簡単に表示できるようになりました。</p>
+
+
+<h2 id="Camera">カメラと動画の拡張</h2>
+
+<p>Android 5.0 では<strong>カメラ用の API</strong> が一新されており、YUV、Bayer RAW などの未加工フォーマットのキャプチャや、露出時間、ISO 感度、フレーム単位のフレーム持続時間などのパラメータ調整が可能です。カメラ パイプラインが完全に同期するようになったことで、対応デバイスを使えば未圧縮のフル解像度 YUV イメージを 30 FPS でキャプチャできます。</p>
+
+<p>イメージと一緒に、ノイズモデルや光情報などのメタデータをカメラからキャプチャすることもできます。</p>
+
+<p>ネットワーク経由で動画ストリームを送信するアプリでは、H.265 <strong>HEVC(High Efficiency Video Coding)</strong>を利用して動画データのエンコードとデコードを最適化できるようになりました。 </p>
+
+<p>Android 5.0 には<strong>マルチメディア トンネリング</strong>のサポートも追加されており、超高解像度(4K)のコンテンツを楽しむための最適な環境を提供するほか、圧縮された音声データと動画データを一緒に再生することも可能です。 </p>
+
+
+
+<div class="figure" style="width:320px; margin:1em 0 0 20px;padding-left:2em;">
+<img style="float:right; margin:0 1em 1em 2em" src="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png" srcset="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png 2x" alt="" width="300" />
+<p class="img-caption">個人用と仕事用のアプリをまとめて表示し、バッジで簡単に識別できます。</p>
+</div>
+
+
+<h2 id="Work">職場での Android</h2>
+
+<p>企業環境において BYOD(Bring-Your-Own-Device)を実現するには、<a href="{@docRoot}about/versions/android-5.0.html#Enterprise">管理されたプロビジョニング手続き</a>によって端末の安全なワーク プロフィールを作成する必要があります。ランチャー内のアプリにワークバッジが表示されている場合は、そのアプリがワーク プロフィール内で IT 管理者によって管理されていることを表します。</p>
+
+<p>通知の表示は個人プロフィールとワーク プロフィールが 1 つに統合されていますが、データはプロフィール別に分けて管理されます。同じアプリを両方のプロフィールで使用しても、それぞれのデータは別々に保管されます。</p>
+
+<p>会社所有の端末は、IT 管理者が新しい端末として登録して<a href="{@docRoot}about/versions/android-5.0.html#DeviceOwner">端末所有者</a>を設定します。会社所有の端末にグローバル端末設定を定義する端末所有者アプリをインストールすることで、従業員はその端末を持ち出すことができるようになります。</p>
+
+
+
+<h2 id="ScreenCapture">画面のキャプチャと共有</h2>
+
+<p>Android 5.0 では、アプリに画面キャプチャや画面共有の機能を追加できます。 </p>
+
+<p>ユーザーの承諾が得られれば、画面から安全性の低い動画をキャプチャしてネットワークに配信することも可能です。</p>
+
+
+<h2 id="Sensors">新しいタイプのセンサー</h2>
+
+<p>Android 5.0 には、新たに<strong>傾き検出</strong>センサーが追加され、対応デバイスでの操作の認識精度が向上しました。また、<strong>心拍数センサー</strong>も追加され、デバイスに接触している人の心拍数を記録できるようになりました。 </p>
+
+<p>新しい<strong>操作複合センサー</strong>を使用すると、「ウェイクアップ」(オンにする)ジェスチャー、「ピックアップ」(手に取る)ジェスチャー、「グランス」(ちらりと見る)ジェスチャーなどの特殊な操作を検出できます。<em></em><em></em><em></em></p>
+
+
+
+<h2 id="WebView">Chromium WebView</h2>
+
+<div style="float:right;margin:1em 2em 1em 2em;">
+ <img src="/images/kk-chromium-icon.png" alt="" height="160" style="margin-bottom:0em;">
+</div>
+
+<p>Android 5.0 の初期リリースには、Chromium M37 リリースをベースとした Chromium for {@link android.webkit.WebView} が含まれており、これにより <strong>WebRTC</strong>、<strong>WebAudio</strong>、<strong>WebGL</strong> がサポートされます。 </p>
+
+<p>Chromium M37 には、すべての <strong>Web Components</strong> 仕様(Custom Elements、Shadow DOM、HTML Imports、Templates)のネイティブ サポートも含まれています。つまり、<a href="http://polymer-project.org/">Polymer</a> とその <a href="https://www.polymer-project.org/docs/elements/material.html">Material Design 要素</a>を WebView で、Polyfill なしで使用できるということです。</p>
+
+<p>Android 4.4 以降の WebView は Chromium をベースにしていますが、Chromium レイヤは今後は Google Play から更新できるようになります。</p>
+
+<p>Chromium の新バージョンがリリースされたとき、Android 5.0 以上で WebView を使用しているアプリのウェブ API の更新やバグ修正がある場合は、ユーザーが Google Play から更新することで WebView の最新の拡張とバグ修正を確実に適用できます。</p>
+
+
+
+<h2 id="Accessibility">ユーザー補助機能と入力</h2>
+
+<p>新しいユーザー補助機能 API を使用すると、視覚に障がいのないユーザーが操作できる画面上のウィンドウのプロパティに関する詳しい情報を取得し、UI 要素の標準入力操作とカスタム入力操作を定義できます。</p>
+
+<p>新しい IME(Input Method Editor)API を使用すると、入力方法から直接他の IME に切り替えることができます。</p>
+
+
+
+<h2 id="Battery">省電力アプリ用のツール</h2>
+
+<p>新しい<strong>ジョブ スケジューリング</strong> API を使用すると、システムのジョブの実行を延期することで電池消費量を最適化できます。延期したジョブは、後で実行するように指定したり、特定の条件(充電中、Wi-Fi 接続時など)を満たしたときに実行したりできます。</p>
+
+<p>新たに追加された <code>dumpsys batterystats</code> コマンドで<strong>電池の使用統計情報</strong>を生成すると、システム全体での電池使用状況や、アプリが電池使用量にどの程度影響しているかを理解できます。電池が消費されたイベントの履歴、UID やシステム コンポーネントごとのおおよその消費電力量なども把握できます。</p>
+
+<img src="{@docRoot}images/versions/battery_historian.png" srcset="{@docRoot}images/versions/battery_historian@2x.png 2x" alt="" width="760" height="462" />
+<p class="img-caption">新しい電池履歴ツールを使用すると、<code>dumpsys batterystats</code> で生成した統計情報を視覚化でき、電池関連のデバッグに便利です。このツールは <a href="https://github.com/google/battery-historian">https://github.com/google/battery-historian</a> から入手できます。</p>
diff --git a/docs/html-intl/intl/ko/about/versions/android-5.0.jd b/docs/html-intl/intl/ko/about/versions/android-5.0.jd
new file mode 100644
index 0000000..48d542e
--- /dev/null
+++ b/docs/html-intl/intl/ko/about/versions/android-5.0.jd
@@ -0,0 +1,636 @@
+page.title=Android 5.0 API
+excludeFromSuggestions=true
+sdk.platform.version=5.0
+sdk.platform.apiLevel=21
+@jd:body
+
+
+<div id="qv-wrapper">
+<div id="qv">
+
+<h2>이 도움말에서 다루는 내용 <a href="#" onclick="hideNestedItems('#toc44',this);return false;" class="header-toggle"> <span class="more">더보기</span> <span class="less" style="display:none">간략히 보기</span></a></h2>
+
+<ol id="toc44" class="hide-nested">
+ <li><a href="#ApiLevel">타겟 API 수준 업데이트</a></li>
+ <li><a href="#Behaviors">중요 동작 변경사항</a>
+ <ol>
+ <li><a href="#ART">새 ART(Android 런타임)에서 앱을 테스트하지 않은 경우...</a></li>
+ <li><a href="#BehaviorNotifications">앱에서 알림을 구현하는 경우...</a></li>
+ <li><a href="#BehaviorMediaControl">앱에서 RemoteControlClient를 사용하는 경우...</a></li>
+<li><a href="#BehaviorGetRecentTasks">앱에서 getRecentTasks()를 사용하는 경우...</a></li>
+<li><a href="#64BitSupport">Android NDK(기본 개발 키트)를 사용 중인 경우...</a></li>
+<li><a href="#BindService">앱이 서비스에 결합된 경우...</a></li>
+<li><a href="#BehaviorWebView">앱에서 WebView를 사용하는 경우...</a></li>
+ </ol>
+ </li>
+ <li><a href="#UI">사용자 인터페이스</a>
+ <ol>
+ <li><a href="#MaterialDesign">머티리얼 디자인 지원</a></li>
+ <li><a href="#Recents">최근 화면의 동시 문서 및 액티비티</a></li>
+ <li><a href="#WebView">WebView 업데이트</a></li>
+ <li><a href="#ScreenCapture">화면 캡처 및 공유</a></li>
+ </ol>
+ </li>
+ <li><a href="#Notifications">알림</a>
+ <ol>
+ <li><a href="#LockscreenNotifications">잠금 화면 알림</a></li>
+ <li><a href="#NotificationsMetadata">알림 메타데이터</a></li>
+ </ol>
+ </li>
+ <li><a href="#Graphics">그래픽</a>
+ <ol>
+ <li><a href="#OpenGLES-3-1">OpenGL ES 3.1 지원</a></li>
+ <li><a href="#AndroidExtensionPack">Android 확장 프로그램 팩</a></li>
+ </ol>
+ </li>
+ <li><a href="#Media">미디어</a>
+ <ol>
+ <li><a href="#Camera-v2">고급 카메라 기능을 위한 카메라 API</a></li>
+ <li><a href="#AudioPlayback">오디오 재생</a></li>
+ <li><a href="#MediaPlaybackControl">미디어 재생 컨트롤</a></li>
+ <li><a href="#MediaBrowsing">미디어 탐색</a></li>
+ </ol>
+ </li>
+ <li><a href="#Storage">저장소</a>
+ <ol>
+ <li><a href="#DirectorySelection">디렉토리 선택</a></li>
+ </ol>
+ </li>
+ <li><a href="#Wireless">무선 및 연결</a>
+ <ol>
+ <li><a href="#Multinetwork">여러 네트워크 연결</a></li>
+ <li><a href="#BluetoothBroadcasting">블루투스 브로드캐스팅</a></li>
+ <li><a href="#NFCEnhancements">NFC 개선사항</a></li>
+ </ol>
+ </li>
+ <li><a href="#Power">프로젝트 Volta</a>
+ <ol>
+ <li><a href="#JobScheduler">작업 예약</a></li>
+ <li><a href="#PowerMeasurementTools">배터리 사용량을 위한 개발자 도구</a>
+ </ol>
+ </li>
+ <li><a href="#Enterprise">업무 및 교육을 위한 Android</a>
+ <ol>
+ <li><a href="#ManagedProvisioning">관리되는 프로비저닝</a></li>
+ <li><a href="#DeviceOwner">기기 소유자</a></li>
+ <li><a href="#ScreenPinning">화면 고정</a></li>
+ </ol>
+ </li>
+ <li><a href="#System">시스템</a>
+ <ol>
+ <li><a href="#AppUsageStatistics">앱 사용량 통계</a></li>
+ </ol>
+ </li>
+ <li><a href="#Printing">인쇄 프레임워크</a>
+ <ol>
+ <li><a href="#PDFRender">PDF를 비트맵으로 렌더링</a></li>
+ </ol>
+ </li>
+ <li><a href="#TestingA11y">테스트 및 접근성</a>
+ <ol>
+ <li><a href="#TestingA11yImprovements">테스트 및 접근성 개선사항</a></li>
+ </ol>
+ </li>
+ <li><a href="#IME">IME</a>
+ <ol>
+ <li><a href="#Switching">더 쉽게 입력 언어를 전환</a></li>
+ </ol>
+ </li>
+ <li><a href="#Manifest">매니페스트 선언</a>
+ <ol>
+ <li><a href="#ManifestFeatures">선언 가능한 필수 기능</a></li>
+ <li><a href="#Permissions">사용자 권한</a></li>
+ </ol>
+ </li>
+</ol>
+
+<h2>API Differences</h2>
+<ol>
+<li><a href="{@docRoot}sdk/api_diff/21/changes.html">API level 20 to 21 &raquo;</a> </li>
+<li><a href="{@docRoot}sdk/api_diff/preview-21/changes.html">L Developer Preview to 21 &raquo;</a> </li>
+</ol>
+
+<h2>See Also</h2>
+<ol>
+<li><a href="{@docRoot}about/versions/android-5.0-changes.html">Android 5.0 Behavior Changes</a> </li>
+<li><a href="{@docRoot}about/versions/lollipop.html">Android Lollipop Highlights</a> </li>
+</ol>
+
+</div>
+</div>
+
+<p>API 수준: {@sdkPlatformApiLevel}</p>
+
+<p>Android 5.0(<a href="{@docRoot}reference/android/os/Build.VERSION_CODES.html#LOLLIPOP">LOLLIPOP</a>)에서는 사용자와 앱 개발자를 위한 새 기능을 제공합니다. 이 문서에서는 가장 주목할 만한 새 API에 대해 안내해 줍니다.</p>
+
+<p>상위 수준에서 새 플랫폼 기능을 확인하려면 <a href="{@docRoot}about/versions/lollipop.html">Android Lollipop 주요 기능</a>을 참조하세요.</p>
+
+
+<h3 id="Start">개발 시작</h3>
+
+<p>Android 5.0용 앱 개발을 시작하려면 먼저 <a href="{@docRoot}sdk/index.html">Android SDK를 다운로드</a>해야 합니다. 그런 다음 <a href="{@docRoot}tools/help/sdk-manager.html">SDK 관리자</a>를 사용하여 Android 5.0 SDK 플랫폼과 시스템 이미지를 다운로드합니다.</p>
+
+
+<h3 id="ApiLevel">타겟 API 수준 업데이트</h3>
+
+<p>Android {@sdkPlatformVersion}을 실행하는 기기에서 앱을 더욱 최적화하려면 <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a>을 <code>"{@sdkPlatformApiLevel}"</code>로 설정하고 Android {@sdkPlatformVersion} 시스템 이미지에 앱을 설치한 다음, 앱을 테스트하고 이러한 변경사항으로 업데이트된 앱을 게시합니다.</p>
+
+<p>이전 버전을 지원하면서 Android {@sdkPlatformVersion} API를 사용할 수도 있습니다. <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a>에서 지원하지 않는 API를 실행하기 전에 시스템 API 수준을 확인하는 코드에 조건을 추가하면 됩니다. 하위 호환성을 유지하는 방법에 대해 자세히 알아보려면 <a href="{@docRoot}training/basics/supporting-devices/platforms.html">여러 플랫폼 버전 지원</a>을 참조하세요.</p>
+
+<p>API 수준이 작동하는 방식에 대한 자세한 내용은 <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">API 수준은 무엇인가요?</a>를 읽어 보세요.</p>
+
+<h2 id="Behaviors">중요 동작 변경사항</h2>
+
+<p>이전에 Android용 앱을 게시한 적이 있는 경우 앱이 Android 5.0 변경사항에 의해 영향을 받을 수 있으므로 주의해야 합니다.</p>
+
+<h3 id="ART">새 ART(Android 런타임)에서 앱을 테스트하지 않은 경우...</h3>
+
+<p>4.4 출시 버전에는 새 실험용 ART(Android 런타임)가 도입되었습니다. 4.4 이전 버전에서는 ART가 선택사항이었고 기본 런타임은 Dalvik으로 설정되었습니다. Android 5.0에서는 이제 ART가 기본 런타임입니다.</p>
+
+<p>ART의 새 기능에 대한 개요는 <a href="https://source.android.com/devices/tech/dalvik/art.html">ART 소개</a>를 참조하세요. 몇 가지 주요한 새 기능은 다음과 같습니다.</p>
+
+<ul>
+ <li>AOT(Ahead-of-time) 컴파일</li>
+ <li>개선된 GC(가비지 컬렉션)</li>
+ <li>개선된 디버깅 지원</li>
+</ul>
+
+<p>대부분의 Android 앱은 이전과 같이 ART에서도 작동해야 합니다. 하지만 Dalvik에서 작동하던 일부 기능은 ART에서 작동하지 않습니다. 가장 중요한 문제를 확인하려면 <a href="{@docRoot}guide/practices/verifying-apps-art.html">ART(Android 런타임)에서 앱 동작 확인</a>을 참조하세요. 다음과 같은 경우 특히 주의하세요.</p>
+
+<ul>
+ <li>앱이 JNI(자바 기본 인터페이스)를 사용하여 C/C++ 코드를 실행하는 경우</li>
+ <li>비표준 코드를 생성하는 개발 도구(예: 몇몇 난독화 도구)를 사용하는 경우</li>
+ <li>가비지 컬렉션 압축과 호환되지 않는 기능을 사용하는 경우 (ART는 현재 가비지 컬렉션 압축을 구현하지 않지만 Android 오픈소스 프로젝트에서 개발 중임)</li>
+</ul>
+
+<h3 id="BehaviorNotifications">앱에서 알림을 구현하는 경우...</h3>
+
+<p>알림이 다음과 같은 Android 5.0 변경사항을 고려하여 구현되는지 확인합니다. Android 5.0 이상에서 알림을 디자인하는 방법에 대해 자세히 알아보려면 <a href="{@docRoot}design/patterns/notifications.html">알림 디자인 가이드</a>를 참조하세요.
+</p>
+
+<h4 id="NotificationsMaterialDesignStyle">머티리얼 디자인 스타일</h4>
+<p>알림은 새 머티리얼 디자인 위젯과 어울리도록 흰색(또는 매우 밝은 색) 배경 위에 어두운 텍스트로 표시됩니다. 모든 알림이 새 색상 구성에서 올바르게 표시되는지 확인하세요. 알림이 올바르게 표시되지 않으면 다음과 같이 수정합니다.</p>
+
+<ul>
+ <li>{@link android.app.Notification.Builder#setColor(int) setColor()}를 사용하여 아이콘 이미지 뒤의 원에 강조 색상을 설정합니다. </li>
+ <li>색상을 포함하는 애셋을 업데이트하거나 제거합니다. 시스템은 작업 아이콘 및 기본 알림 아이콘에서 알파 이외의 모든 채널을 무시합니다. 알파 채널인 아이콘만 표시된다고 가정하면 됩니다. 시스템에서 알림 아이콘은 흰색으로, 작업 아이콘은 어두운 회색으로 표시합니다.</li>
+</ul>
+
+<h4 id="NotificationsSoundVibration">소리 및 진동</h4>
+<p>현재 {@link android.media.Ringtone}, {@link android.media.MediaPlayer} 또는 {@link android.os.Vibrator} 클래스를 사용하여 알림에 소리 및 진동을 추가한 경우, 이 코드를 제거해야 시스템이 <em>우선순위</em> 모드에서 알림을 올바르게 표시할 수 있습니다. 대신 {@link android.app.Notification.Builder} 메소드를 사용하여 소리 및 진동을 추가합니다.</p>
+
+<p>기기를 {@link android.media.AudioManager#RINGER_MODE_SILENT RINGER_MODE_SILENT}로 설정하면 기기가 새 우선순위 모드로 설정됩니다. 기기를 {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_NORMAL} 또는 {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_VIBRATE}로 설정하면 기기의 우선순위 모드가 종료됩니다.</p>
+
+<p>이전에는 Android에서 태블릿 기기의 볼륨을 조절하기 위해 마스터 스트림으로 {@link android.media.AudioManager#STREAM_MUSIC STREAM_MUSIC}을 사용했습니다. Android 5.0에서는 휴대전화 및 태블릿 기기의 마스터 볼륨 스트림이 통합되었으며 {@link android.media.AudioManager#STREAM_RING STREAM_RING} 또는 {@link android.media.AudioManager#STREAM_NOTIFICATION STREAM_NOTIFICATION}에서 제어합니다.</p>
+
+<h4 id="NotificationsLockscreenVisibility">잠금 화면 표시 여부</h4>
+<p>기본적으로 Android 5.0에서는 사용자의 잠금 화면에 알림이 표시됩니다. 사용자는 민감한 정보가 노출되지 않도록 선택할 수 있습니다. 이 경우 시스템에서 알림에 표시되는 텍스트를 자동으로 수정합니다. 이렇게 수정되는 알림을 맞춤설정하려면 {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()}을 사용합니다.</p>
+<p>알림에 개인정보가 포함되지 않았거나 알림에서 미디어 재생 컨트롤을 허용하려는 경우 {@link android.app.Notification.Builder#setVisibility(int) setVisibility()} 메소드를 호출하고 알림의 표시 수준을 {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}으로 설정합니다.
+</p>
+
+<h4 id="NotificationsMediaPlayback">미디어 재생</h4>
+<p>미디어 재생 상태 또는 이동 컨트롤을 표시하는 알림을 구현하는 경우 기존 {@link android.widget.RemoteViews.RemoteView} 개체 대신 새 {@link android.app.Notification.MediaStyle} 템플릿을 사용하는 것이 좋습니다. 어떤 방식을 선택하든 알림의 표시 여부를 {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}으로 설정하여 잠금 화면에서 컨트롤에 액세스할 수 있도록 합니다. Android 5.0부터 시스템이 잠금 화면에서 더 이상 {@link android.media.RemoteControlClient} 개체를 표시하지 않습니다. 자세한 내용은 <a href="#BehaviorMediaControl">앱에서 RemoteControlClient를 사용하는 경우</a>를 참조하세요.</p>
+
+<h4 id="NotificationsHeadsup">헤드업 알림</h4>
+<p>이제 기기를 사용 중일 때(즉, 기기가 잠금 해제 상태이고 화면이 켜져 있는 경우) 작은 플로팅 창(헤드업 알림이라고도 함)에 알림이 표시될 수 있습니다. 이러한 알림은 간결한 형태의 알림과 비슷하게 표시되지만 헤드업 알림에는 작업 버튼도 표시됩니다. 사용자는 사용 중인 앱을 종료하지 않고 헤드업 알림에서 작업을 수행하거나 알림을 닫을 수 있습니다.</p>
+
+<p>다음은 헤드업 알림을 실행할 수 있는 조건의 예입니다.</p>
+
+<ul>
+ <li>사용자의 액티비티가 전체화면 모드인 경우(앱에서 {@link android.app.Notification#fullScreenIntent}를 사용하는 경우)</li>
+ <li>알림이 높은 우선순위를 가지며 벨소리 또는 진동을 사용하는 경우</li>
+</ul>
+
+<p>위와 같은 시나리오에서 앱이 알림을 구현하는 경우 헤드업 알림이 올바르게 표시되는지 확인하세요.</p>
+
+<h3 id="BehaviorMediaControl">앱에서 RemoteControlClient를 사용하는 경우...</h3>
+<p>{@link android.media.RemoteControlClient} 클래스는 이제 사용할 수 없습니다. 가능한 빨리 새 {@link android.media.session.MediaSession} API로 전환하세요.</p>
+
+<p>Android 5.0의 잠금 화면은 {@link android.media.session.MediaSession} 또는 {@link android.media.RemoteControlClient}의 이동 컨트롤을 표시하지 않습니다. 대신 앱에서 알림을 통해 잠금 화면의 미디어 재생 컨트롤을 제공할 수 있습니다. 이를 통해 앱에서 미디어 버튼 표시를 더욱 제어할 수 있게 되며, 잠금 설정 및 해제된 기기에서 사용자에게 일관된 경험을 제공할 수 있게 됩니다.</p>
+
+<p>이를 위해 Android 5.0에는 새 {@link android.app.Notification.MediaStyle} 템플릿이 도입되었습니다. {@link android.app.Notification.MediaStyle}에서 {@link android.app.Notification.Builder#addAction(int, java.lang.CharSequence, android.app.PendingIntent) Notification.Builder.addAction()}을 사용하여 추가한 알림 작업을 앱의 미디어 재생 알림에 삽입된 간단한 버튼으로 전환합니다. 세션 토큰을 {@link android.app.Notification.MediaStyle#setMediaSession(android.media.session.MediaSession.Token) setSession()} 메소드로 전달하여 시스템에 이 알림이 진행 중인 미디어 세션을 제어한다는 것을 알립니다.</p>
+
+<p>알림의 표시 여부를 {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}으로 설정하여 알림이 모든 잠금 화면(보안 또는 비보안)에서 표시되어도 안전함을 나타냅니다. 자세한 내용은 <a href="#LockscreenNotifications">잠금 화면 알림</a>을 참조하세요.</p>
+
+<p>앱이 Android <a href="{@docRoot}tv/index.html">TV</a> 또는 <a href="{@docRoot}wear/index.html">Wear</a> 플랫폼에서 실행되는 경우 미디어 재생 컨트롤을 표시하려면 {@link android.media.session.MediaSession} 클래스를 구현합니다. 또한 앱이 Android 기기에서 미디어 버튼 이벤트를 수신해야 하는 경우 {@link android.media.session.MediaSession}도 구현해야 합니다.</p>
+
+<h3 id="BehaviorGetRecentTasks">앱에서 getRecentTasks()를 사용하는 경우...</h3>
+
+<p>Android 5.0에 새 <em>동시 문서 및 액티비티 작업</em> 기능(아래의 <a href="#Recents">최근 화면에서 동시 문서 및 액티비티</a> 참조)이 도입되면서, 사용자의 개인정보 보호를 개선하기 위해 이제 {@link android.app.ActivityManager#getRecentTasks ActivityManager.getRecentTasks()} 메소드가 사용 중지되었습니다. 하위 호환성을 위해 이 메소드에서는 여전히 관련 데이터의 일부 하위 집합을 반환합니다. 여기에는 호출 애플리케이션의 자체 작업과 가능한 경우 민감하지 않은 일부 기타 작업(예: 홈)이 포함됩니다. 앱에서 이 메소드를 사용하여 자체 작업을 가져오는 경우 {@link android.app.ActivityManager#getAppTasks() getAppTasks()}를 대신 사용하여 정보를 가져오세요.</p>
+
+<h3 id="64BitSupport">Android NDK(기본 개발 키트)를 사용 중인 경우...</h3>
+
+<p>Android 5.0에서는 64비트 시스템을 지원합니다. 64비트 지원을 통해 기존의 32비트 앱을 계속해서 완전하게 지원하면서 주소 공간을 넓히고 성능을 개선했습니다. 또한 64비트 지원으로 암호화를 위한 OpenSSL 성능이 개선되었습니다. 이외에 이 출시 버전에는 새 기본 미디어 NDK API와 함께 기본 OpenGL ES(GLES) 3.1 지원이 도입되었습니다.</p>
+
+<p>Android 5.0에서 제공되는 64비트 지원을 사용하려면 <a href="{@docRoot}tools/sdk/ndk/index.html">Android NDK 페이지</a>에서 NDK 수정 버전 10c를 다운로드하고 설치하세요. NDK의 중요 변경사항 및 버그 수정에 대한 자세한 내용은 수정 버전 10c <a href="{@docRoot}tools/sdk/ndk/index.html#Revisions">출시 노트</a>를 참조하세요.</p>
+
+<h3 id="BindService">앱이 서비스에 결합된 경우...</h3>
+
+<p>이제 {@link android.content.Context#bindService(android.content.Intent, android.content.ServiceConnection, int) Context.bindService()} 메소드에서 명시적 {@link android.content.Intent}를 요구하며 암시적 인텐트가 있는 경우 예외를 발생시킵니다. 앱이 안전한지 확인하려면 {@link android.app.Service}를 시작하거나 결합할 때 명시적 인텐트를 사용하고 서비스를 위한 인텐트 필터를 선언하지 마세요.</p>
+
+<h3 id="BehaviorWebView">앱에서 WebView를 사용하는 경우...</h3>
+
+<p>Android 5.0에서는 앱의 기본 동작이 변경되었습니다.</p>
+<ul>
+<li><strong>앱에서 API 수준 21 이상을 타겟팅하는 경우:</strong>
+ <ul>
+ <li>시스템에서 기본적으로 <a href="https://developer.mozilla.org/en-US/docs/Security/MixedContent" class="external-link">혼합된 콘텐츠</a>와 타사 쿠키를 차단합니다. 혼합된 콘텐츠와 타사 쿠키를 허용하려면 {@link android.webkit.WebSettings#setMixedContentMode(int) setMixedContentMode()} 및 {@link android.webkit.CookieManager#setAcceptThirdPartyCookies(android.webkit.WebView, boolean) setAcceptThirdPartyCookies()} 메소드를 각각 사용합니다.</li>
+ <li>이제 시스템에서 표시할 HTML 문서의 부분을 지능적으로 선택합니다. 이 새 기본 동작을 통해 메모리 사용량을 줄이고 성능을 개선할 수 있습니다. 문서 전체를 한 번에 렌더링하려면 {@link android.webkit.WebView#enableSlowWholeDocumentDraw()}를 호출하여 이 최적화 방식을 사용 중지합니다.</li>
+ </ul>
+</li>
+<li><strong>앱에서 API 수준 20 이하를 타겟팅하는 경우:</strong> 시스템에서 혼합된 콘텐츠와 타사 쿠키를 허용하며 항상 문서 전체를 한 번에 렌더링합니다.</li>
+</ul>
+
+<h2 id="UI">사용자 인터페이스</h2>
+
+<h3 id="MaterialDesign">머티리얼 디자인 지원</h3>
+
+<p>곧 출시되는 버전에는 Android의 새 <em>머티리얼 디자인</em> 스타일에 대한 지원이 추가되었습니다. 머티리얼 디자인을 사용하면 시각적으로 역동적이고 사용자가 자연스럽게 느낄 수 있는 UI 요소의 전환을 포함한 앱을 만들 수 있습니다. 지원에는 다음이 포함됩니다.</p>
+
+<ul>
+
+ <li>머티리얼 테마</li>
+ <li>그림자 보기</li>
+ <li>{@link android.support.v7.widget.RecyclerView} 위젯</li>
+ <li>드로어블 애니메이션 및 스타일 효과</li>
+ <li>머티리얼 디자인 애니메이션 및 액티비티 전환 효과</li>
+ <li>보기 상태에 따른 보기 속성의 애니메이터</li>
+ <li>제어할 수 있는 색상 팔레트로 맞춤설정할 수 있는 UI 위젯과 앱 막대</li>
+ <li>XML 벡터 그래픽을 기반으로 하는 애니메이션 및 애니메이션 이외 드로어블</li>
+</ul>
+
+<p>앱에 머티리얼 디자인 기능을 추가하는 방법에 대해 자세히 알아보려면 <a href="{@docRoot}training/material/index.html">머티리얼 디자인</a>을 참조하세요.</p>
+
+<h3 id="Recents">최근 화면의 동시 문서 및 액티비티</h3>
+
+<p>이전 출시 버전에서는 <a href="{@docRoot}guide/components/recents.html">최근 화면</a>에 각 앱에 대해 사용자가 가장 최근에 상호작용한 하나의 작업만 표시될 수 있었습니다. 이제 앱에서 문서의 추가적인 동시 액티비티에 필요한 만큼 더 많은 작업을 열 수 있습니다. 이 기능은 최근 화면에서 사용자가 개별 액티비티와 문서 간에 빠르게 전환할 수 있도록 하여 멀티태스킹을 용이하게 하며, 모든 앱에서 일관된 전환 경험을 제공해 줍니다. 이러한 동시 작업의 예로는 웹브라우저 앱에서 열려 있는 탭, 생산성 앱의 문서, 게임에서의 동시 대결 또는 메시지 앱에서의 채팅이 있습니다. 앱은 {@link android.app.ActivityManager.AppTask} 클래스를 통해 작업을 관리할 수 있습니다.</p>
+
+<p>논리 중단을 삽입하여 시스템이 액티비티를 새 작업으로 처리하도록 하려면, {@link android.app.Activity#startActivity(android.content.Intent) startActivity()}로 액티비티를 실행할 때 {@link android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT}를 사용합니다. 매니페스트에서 <a href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a> 요소의 {@code documentLaunchMode} 속성을 {@code "intoExisting"} 또는 {@code "always"}로 설정하여 이 동작을 유도할 수도 있습니다.</p>
+
+<p>최근 화면이 지저분해지지 않게 하려면 앱에서 화면에 표시할 수 있는 작업의 최대 개수를 설정하면 됩니다. 설정하려면 <a href="{@docRoot}guide/topics/manifest/application-element.html">&lt;application&gt;</a> 속성 {@link android.R.attr#maxRecents android:maxRecents}를 설정합니다. 현재 사용자당 최대 50개의 작업을 지정할 수 있습니다(기기의 RAM이 낮은 경우는 25개)입니다.</a></p>
+
+<p>최근 화면의 작업은 재부팅해도 지속되도록 설정할 수 있습니다. 지속 동작을 제어하려면 <a href="{@docRoot}reference/android/R.attr.html#persistableMode">android:persistableMode</a> 속성을 사용합니다. 또한 최근 화면에서 {@link android.app.Activity#setTaskDescription(android.app.ActivityManager.TaskDescription) setTaskDescription()} 메소드를 호출하여 액티비티의 색상, 라벨, 아이콘과 같은 액티비티의 시각적 속성을 변경할 수도 있습니다.</p>
+
+<h3 id="WebView">WebView 업데이트</h3>
+<p>Android 5.0에서는 {@link android.webkit.WebView} 구현을 Chromium M37로 업데이트하여 보안 및 안정성을 개선하고 버그도 수정했습니다. Android 5.0에서 실행되는 {@link android.webkit.WebView}의 기본 사용자 에이전트 문자열이 37.0.0.0을 버전 번호로 통합하도록 업데이트되었습니다.</p>
+
+<p>이 출시 버전에는 {@link android.webkit.PermissionRequest} 클래스가 도입되었습니다. 이를 사용하면 앱에서 {@link android.webkit.WebView} 권한을 부여하여 <a href="https://developer.mozilla.org/en-US/docs/NavigatorUserMedia.getUserMedia" class="external-link">getUserMedia()</a>와 같은 웹 API를 통해 카메라와 마이크 등의 보호된 리소스에 액세스할 수 있습니다. {@link android.webkit.WebView}에 권한을 부여하려면 이러한 리소스에 대한 적절한 Android 권한이 앱에 있어야 합니다.</p>
+
+<p>이제 새 <code><a href="{@docRoot}reference/android/webkit/WebChromeClient.html#onShowFileChooser(android.webkit.WebView, android.webkit.ValueCallback<android.net.Uri[]>, android.webkit.WebChromeClient.FileChooserParams)">onShowFileChooser()</a></code> 메소드를 통해 {@link android.webkit.WebView}에서 입력 양식 필드를 사용할 수 있고, 파일 선택기를 실행하여 Android 기기에서 이미지 및 파일을 선택할 수 있습니다.</p>
+
+<p>또한 이 출시 버전에서는 <a href="http://webaudio.github.io/web-audio-api/" class="external-link">WebAudio</a>, <a href="https://www.khronos.org/webgl/" class="external-link">WebGL</a>, <a href="http://www.webrtc.org/" class="external-link">WebRTC</a> 개방형 표준을 지원합니다. 이 출시 버전에 포함된 새 기능에 대해 자세히 알아보려면 <a href="https://developer.chrome.com/multidevice/webview/overview" class="external-link">Android용 WebView</a>를 참조하세요.</p>
+
+<h3 id="ScreenCapture">화면 캡처 및 공유</h3>
+<p>Android 5.0에서는 새 {@link android.media.projection} API를 통해 앱에 화면 캡처 및 화면 공유 기능을 추가할 수 있습니다. 예를 들어 이 기능은 동영상 회의 앱에서 화면 공유를 사용하려는 경우 유용합니다.</p>
+
+<p>새 {@link android.media.projection.MediaProjection#createVirtualDisplay(java.lang.String, int, int, int, int, android.view.Surface, android.hardware.display.VirtualDisplay.Callback, android.os.Handler) createVirtualDisplay()} 메소드를 사용하면 앱에서 기본 화면(기본 디스플레이)의 콘텐츠를 {@link android.view.Surface} 개체로 캡처할 수 있으므로 앱에서 캡처한 콘텐츠를 네트워크를 통해 전송할 수 있습니다. 이 API는 비보안 화면 콘텐츠만 캡처할 수 있으며 시스템 오디오에는 적용되지 않습니다. 화면 캡처를 시작하려면 먼저 앱에서 사용자의 권한을 요청해야 하며, {@link android.content.Intent}({@link android.media.projection.MediaProjectionManager#createScreenCaptureIntent()} 메소드를 통해 가져옴)를 사용하는 화면 캡처 대화상자를 실행하여 권한을 요청할 수 있습니다.</p>
+
+<p>새 API를 사용하는 방법에 대한 예는 샘플 프로젝트의 {@code MediaProjectionDemo} 클래스를 참조하세요.</p>
+
+<h2 id="Notifications">알림</h2>
+
+<h3 id="LockscreenNotifications">잠금 화면 알림</h3>
+<p>Android 5.0의 잠금 화면에는 알림을 표시할 수 있습니다. 사용자는 <em>설정</em>을 통해 민감한 알림 내용의 보안 잠금 화면 표시 여부를 선택할 수 있습니다.</p>
+
+<p>앱에서 보안 잠금 화면에 알림이 표시될 때 세부내용의 표시 수준을 제어할 수 있습니다. 표시 수준을 제어하려면 {@link android.app.Notification.Builder#setVisibility(int) setVisibility()}를 호출하고 다음 값 중 하나를 지정합니다.</p>
+
+<ul>
+<li>{@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}: 알림 아이콘과 같은 기본 정보를 표시하고 알림의 전체 내용은 숨깁니다.</li>
+<li>{@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}: 알림의 전체 내용을 표시합니다.</li>
+<li>{@link android.app.Notification#VISIBILITY_SECRET VISIBILITY_SECRET}: 알림 아이콘을 포함하여 아무것도 표시하지 않습니다.</li>
+</ul>
+
+<p>표시 수준이 {@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}인 경우 개인 세부정보를 숨기는 알림 내용의 수정된 버전을 제공할 수도 있습니다. 예를 들어 SMS 앱에서 '3개의 새 메시지가 있습니다'라는 알림을 표시하면서 메시지 내용과 보낸 사람을 숨길 수도 있습니다. 이러한 대체 알림을 제공하려면 먼저 {@link android.app.Notification.Builder}를 사용하여 대체 알림을 만듭니다. 비공개 알림 개체를 만드는 경우 {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()} 메소드를 통해 비공개 알림 개체에 대체 알림을 첨부합니다.</p>
+
+<h3 id="NotificationsMetadata">알림 메타데이터</h3>
+<p>Android 5.0에서는 앱 알림에 연결된 메타데이터를 사용하여 알림을 더욱 지능적으로 정렬합니다. 메타데이터를 설정하려면 알림을 생성할 때 {@link android.app.Notification.Builder}에서 다음 메소드를 호출합니다.</p>
+
+<ul>
+<li>{@link android.app.Notification.Builder#setCategory(java.lang.String) setCategory()}: 기기가 <em>우선순위</em> 모드일 때 앱 알림을 처리하는 방식을 시스템에 알립니다(예: 알림이 수신 전화, 메시지 또는 알람을 표시하는 경우).
+<li>{@link android.app.Notification.Builder#setPriority(int) setPriority()}: 알림을 일반 알림보다 더 중요한 또는 덜 중요한 알림으로 표시합니다. 알림에 소리나 진동도 포함된 경우, 우선순위 필드가 {@link android.app.Notification#PRIORITY_MAX PRIORITY_MAX} 또는 {@link android.app.Notification#PRIORITY_HIGH PRIORITY_HIGH}로 설정된 알림은 작은 플로팅 창에 표시됩니다.</li>
+<li>{@link android.app.Notification.Builder#addPerson(java.lang.String) addPerson()}: 알림과 관련된 사람을 한 명 이상 추가할 수 있습니다. 앱에서 이 메소드를 사용하여 지정한 사람의 알림을 모두 묶어야 하는지 또는 이 사람이 보낸 알림을 더 중요한 알림으로 표시해야 하는지를 시스템에 알릴 수 있습니다.</li>
+</ul>
+
+<h2 id="Graphics">그래픽</h2>
+
+<h3 id="OpenGLES-3-1">OpenGL ES 3.1 지원</h3>
+<p>Android 5.0에는 자바 인터페이스와 OpenGL ES 3.1에 대한 기본 지원이 추가되었습니다. OpenGL ES 3.1에서 제공하는 주요한 새 기능은 다음과 같습니다.</p>
+
+<ul>
+<li>셰이더 계산
+<li>셰이더 개체 분리
+<li>간접 그리기 명령
+<li>멀티샘플 및 스텐실 텍스처
+<li>셰이딩 언어 개선
+<li>고급 혼합 모드 및 디버깅을 위한 확장 프로그램
+<li>OpenGL ES 2.0 및 3.0과의 하위 호환성
+</ul>
+
+<p>Android의 OpenGL ES 3.1용 자바 인터페이스는 {@link android.opengl.GLES31}과 함께 제공됩니다. OpenGL ES 3.1을 사용하는 경우 <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> 태그 및 {@code android:glEsVersion} 속성을 사용하여 매니페스트 파일에서 OpenGL을 선언해야 합니다. 예를 들어 다음과 같이 선언합니다.</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:glEsVersion="0x00030001" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<p>런타임에서 기기의 지원되는 OpenGL ES 버전을 확인하는 방법 등 OpenGL ES 사용에 대한 자세한 내용은 <a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL ES API 가이드</a>를 확인하세요.</p>
+
+<h3 id="AndroidExtensionPack">Android 확장 프로그램 팩</h3>
+
+<p>OpenGL ES 3.1 외에, 이 출시 버전에서는 자바 인터페이스와 고급 그래픽 기능에 대한 기본 지원이 포함된 확장 프로그램 팩을 제공합니다. 이러한 확장 프로그램은 Android에서 단일 패키지로 취급합니다. {@code ANDROID_extension_pack_es31a} 확장 프로그램이 있는 경우 앱에서 패키지의 모든 확장 프로그램이 있다고 가정하고, 단일 {@code #extension} 구문을 통해 셰이딩 언어 기능을 사용 설정합니다.</p>
+
+<p>확장 프로그램 팩은 다음을 지원합니다.</p>
+
+<ul>
+<li>셰이더 저장소 버퍼, 이미지, 아토믹에 대한 보증된 프래그먼트 셰이더 지원(OpenGL ES 3.1에서는 프래그먼트 셰이더가 선택사항)</li>
+<li>테셀레이션 및 도형 셰이더</li>
+<li>ASTC(LDR) 텍스처 압축 형식</li>
+<li>샘플당 보간 및 셰이딩</li>
+<li>프레임 버퍼에서 각 색상을 추가하기 위한 여러 가지 혼합 모드</li>
+</ul>
+
+<p>확장 프로그램 팩의 자바 인터페이스는 {@link android.opengl.GLES31Ext}와 함께 제공됩니다. 앱 매니페스트에서 앱이 확장 프로그램 팩을 지원하는 기기에서만 설치되도록 선언할 수 있습니다. 예를 들어 다음과 같이 선언합니다.</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:name=“android.hardware.opengles.aep”
+ android:required="true" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<h2 id="Media">미디어</h2>
+
+<h3 id="Camera-v2">고급 카메라 기능을 위한 카메라 API</h3>
+
+<p>Android 5.0에는 새 <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">android.hardware.camera2</a> API가 도입되어 고품질 사진 캡처 및 이미지 처리가 더욱 쉬워졌습니다. {@link android.hardware.camera2.CameraManager#getCameraIdList() getCameraIdList()}로 시스템에 사용할 수 있는 카메라 기기에 프로그램 방식으로 액세스할 수 있으며, {@link android.hardware.camera2.CameraManager#openCamera(java.lang.String, android.hardware.camera2.CameraDevice.StateCallback, android.os.Handler) openCamera()}로 특정 기기에 연결할 수 있습니다. 이미지 캡처를 시작하려면 {@link android.hardware.camera2.CameraCaptureSession}을 만들고 {@link android.view.Surface} 개체를 지정하여 캡처한 이미지를 전송합니다. 한 장의 사진 또는 한 번에 여러 이미지를 촬영하도록 {@link android.hardware.camera2.CameraCaptureSession}을 구성할 수 있습니다.</p>
+
+<p>새 이미지를 캡처할 때 알림을 받으려면 {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} 리스너를 구현하고 캡처 요청에서 이를 설정합니다. 이제 시스템에서 이미지 캡처 요청을 완료하면 {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} 리스너가 {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback#onCaptureCompleted(android.hardware.camera2.CameraCaptureSession, android.hardware.camera2.CaptureRequest, android.hardware.camera2.TotalCaptureResult) onCaptureCompleted()}에 대한 호출을 수신하고 {@link android.hardware.camera2.CaptureResult}의 이미지 캡처 메타데이터를 제공합니다.</p>
+
+<p>{@link android.hardware.camera2.CameraCharacteristics} 클래스를 사용하면 기기에서 사용할 수 있는 카메라 기능을 감지할 수 있습니다. 개체의 {@link android.hardware.camera2.CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL INFO_SUPPORTED_HARDWARE_LEVEL} 속성은 카메라의 기능 수준을 나타냅니다.</p>
+
+<ul>
+ <li>모든 기기는 최소 {@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY} 하드웨어 수준을 지원하며, 이는 사용 중지된 {@link android.hardware.Camera} API의 수준과 거의 동등한 기능을 가집니다.</li>
+ <li>{@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_FULL INFO_SUPPORTED_HARDWARE_LEVEL_FULL} 하드웨어 수준을 지원하는 기기는 캡처 및 후속 처리를 수동으로 제어할 수 있으며 높은 프레임 속도에서 고해상도 이미지를 캡처할 수 있습니다.</li>
+</ul>
+
+<p>업데이트된 <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">카메라</a> API를 사용하는 방법에 대해 알아보려면 이 출시 버전의 {@code Camera2Basic} 및 {@code Camera2Video} 구현 샘플을 참조하세요.</p>
+
+<h3 id="AudioPlayback">오디오 재생</h3>
+<p>이 출시 버전에는 다음과 같은 {@link android.media.AudioTrack}에 대한 변경사항이 포함되어 있습니다.</p>
+<ul>
+ <li>이제 앱에서 부동 소수점 형식({@link android.media.AudioFormat#ENCODING_PCM_FLOAT ENCODING_PCM_FLOAT})으로 오디오 데이터를 제공할 수 있습니다. 이를 통해 더 큰 음량비, 더 일관된 정밀도 및 더 큰 헤드룸이 가능해졌습니다. 부동 소수점 연산은 중간 과정 계산에 특히 유용합니다. 재생 엔드포인트는 오디오 데이터에 낮은 비트 심도로 정수 형식을 사용합니다 (Android 5.0에서 일부 내부 파이프라인은 아직 부동 소수점이 아님).
+ <li>이제 앱에서 오디오 데이터를 {@link android.media.MediaCodec}에서 제공하는 것과 같은 형식인 {@link java.nio.ByteBuffer}로 제공할 수 있습니다.
+ <li>{@link android.media.AudioTrack#WRITE_NON_BLOCKING WRITE_NON_BLOCKING} 옵션은 일부 앱에서 버퍼링 및 멀티스레딩을 단순화할 수 있습니다.
+</ul>
+
+<h3 id="MediaPlaybackControl">미디어 재생 컨트롤</h3>
+<p>새 알림 및 미디어 API를 사용하면 시스템 UI에서 미디어 재생을 인식하고 앨범 아트를 추출 및 표시하도록 할 수 있습니다. 이제 새 {@link android.media.session.MediaSession} 및 {@link android.media.session.MediaController} 클래스를 통해 UI 및 서비스에서 미디어 재생을 제어하는 것이 더욱 쉬워졌습니다.</p>
+
+<p>새 {@link android.media.session.MediaSession} 클래스는 사용 중지된 {@link android.media.RemoteControlClient} 클래스를 대체하며 이동 컨트롤 및 미디어 버튼 처리에 하나의 콜백 메소드 집합을 제공합니다. 앱이 미디어 재생을 제공하고 Android <a href="{@docRoot}tv/index.html">TV</a> 또는 <a href="{@docRoot}wear/index.html">Wear</a> 플랫폼에서 실행되는 경우, {@link android.media.session.MediaSession} 클래스로 동일한 콜백 메소드를 사용하는 이동 컨트롤을 처리할 수 있습니다.</p>
+
+<p>이제 새 {@link android.media.session.MediaController} 클래스를 사용하여 미디어 컨트롤러 앱을 제작할 수 있습니다. 이 클래스는 스레드 안전성을 보장하면서 앱의 UI 프로세스에서 미디어 재생을 모니터링하고 제어할 수 있는 방법을 제시합다. 컨트롤러를 만들 때 {@link android.media.session.MediaSession.Token} 개체를 지정하여 앱이 기존 {@link android.media.session.MediaSession}과 상호작용할 수 있도록 합니다. {@link android.media.session.MediaController.TransportControls} 메소드를 사용하여 {@link android.media.session.MediaController.TransportControls#play() play()}, {@link android.media.session.MediaController.TransportControls#stop() stop()}, {@link android.media.session.MediaController.TransportControls#skipToNext() skipToNext()} 및 {@link android.media.session.MediaController.TransportControls#setRating(android.media.Rating) setRating()}과 같은 명령을 전송해 해당 세션에서 미디어 재생을 제어할 수 있습니다. 컨트롤러를 사용하면 {@link android.media.session.MediaController.Callback} 개체를 등록하여 세션의 메타데이터 및 상태 변경을 수신할 수도 있습니다.</p>
+
+<p>또한 새 {@link android.app.Notification.MediaStyle} 클래스를 사용하여 미디어 세션에 연결된 재생 컨트롤을 허용하는 리치 알림을 생성할 수 있습니다.</p>
+
+<h3 id="MediaBrowsing">미디어 탐색</h3>
+<p>Android 5.0에는 새 <a href="{@docRoot}reference/android/media/browse/package-summary.html">android.media.browse</a> API를 통해 앱에서 다른 앱의 미디어 콘텐츠 라이브러리를 탐색할 수 있는 기능이 도입되었습니다. 앱의 미디어 콘텐츠를 노출하려면 {@link android.service.media.MediaBrowserService} 클래스를 확장합니다. {@link android.service.media.MediaBrowserService} 구현하면서 {@link android.media.session.MediaSession.Token}에 대한 액세스 권한을 제공해야 서비스를 통해 제공된 미디어 콘텐츠를 앱에서 재생할 수 있습니다.</p>
+<p>미디어 브라우저 서비스와 상호작용하려면 {@link android.media.browse.MediaBrowser} 클래스를 사용합니다. {@link android.media.browse.MediaBrowser} 인스턴스를 만들 때 {@link android.media.session.MediaSession}의 구성요소 이름을 지정합니다. 이 브라우저 인스턴스를 사용하면 앱에서 서비스에 연결할 수 있고, {@link android.media.session.MediaSession.Token} 개체를 가져와 서비스를 통해 노출된 콘텐츠를 재생할 수 있습니다.</p>
+
+<h2 id="Storage">저장소</h2>
+
+<h3 id="DirectorySelection">디렉토리 선택</h3>
+
+<p>Android 5.0에서는 <a href="{@docRoot}guide/topics/providers/document-provider.html">저장소 액세스 프레임워크</a>를 확장하여 사용자가 전체 디렉토리 하위 트리를 선택할 수 있으며, 각 항목에 대한 사용자 확인 없이 포함된 모든 문서에 대한 읽기/쓰기 액세스 권한을 앱에 부여합니다.</p>
+
+<p>디렉토리 하위 트리를 선택하려면 {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE OPEN_DOCUMENT_TREE} 인텐트를 만들어 전송합니다. 시스템에서 하위 트리 선택을 지원하는 모든 {@link android.provider.DocumentsProvider} 인스턴스를 표시하며, 사용자가 디렉토리를 탐색 및 선택할 수 있게 됩니다. 반환된 URI가 선택된 하위 트리에 대한 액세스를 표시합니다. 그러면 {@link android.provider.DocumentsContract#buildChildDocumentsUriUsingTree(android.net.Uri, java.lang.String) buildChildDocumentsUriUsingTree()} 및 {@link android.provider.DocumentsContract#buildDocumentUriUsingTree(android.net.Uri, java.lang.String) buildDocumentUriUsingTree()}를 {@link android.content.ContentResolver#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String) query()}와 함께 사용하여 하위 트리를 탐색할 수 있습니다.</p>
+
+<p>새 {@link android.provider.DocumentsContract#createDocument(android.content.ContentResolver, android.net.Uri, java.lang.String, java.lang.String) createDocument()} 메소드를 사용하면 하위 트리의 모든 위치에서 새 문서나 디렉토리를 만들 수 있습니다. 기존 문서를 관리하려면 {@link android.provider.DocumentsContract#renameDocument(android.content.ContentResolver, android.net.Uri, java.lang.String) renameDocument()} 및 {@link android.provider.DocumentsProvider#deleteDocument(java.lang.String) deleteDocument()}를 사용합니다. 게시 전에 {@link android.provider.DocumentsContract.Document#COLUMN_FLAGS COLUMN_FLAGS}에서 이러한 호출에 대한 제공업체 지원을 확인합니다.</p>
+
+<p>{@link android.provider.DocumentsProvider}를 구현하고 있고 하위 트리 선택을 지원하고자 하는 경우 {@link android.provider.DocumentsProvider#isChildDocument(java.lang.String, java.lang.String) isChildDocument()}를 구현하고 {@link android.provider.DocumentsContract.Root#FLAG_SUPPORTS_IS_CHILD FLAG_SUPPORTS_IS_CHILD}를 {@link android.provider.DocumentsContract.Root#COLUMN_FLAGS COLUMN_FLAGS}에 추가합니다.</p>
+
+<p>또한 Android 5.0에는 공유 저장소의 새 패키지 전용 디렉토리가 도입되었습니다. 앱에서 {@link android.provider.MediaStore}에 포함될 미디어 파일을 이 디렉토리에 저장할 수 있습니다. 새 {@link android.content.Context#getExternalMediaDirs()}는 공유된 모든 저장 기기에서 이 디렉토리의 경로를 반환합니다. {@link android.content.Context#getExternalFilesDir(java.lang.String) getExternalFilesDir()}과 비슷하게 앱에서 반환된 경로에 액세스하는 데 추가 권한이 필요하지 않습니다. 플랫폼에서 이 디렉토리에서 새 미디어가 있는지 주기적으로 스캔하지만 {@link android.media.MediaScannerConnection}을 사용하여 새 콘텐츠를 명시적으로 검색할 수도 있습니다.</p>
+
+<h2 id="Wireless">무선 및 연결</h2>
+
+<h3 id="Multinetwork">여러 네트워크 연결</h3>
+<p>Android 5.0에서는 앱이 특정 기능이 있는 사용 가능한 네트워크를 동적으로 스캔하고 이러한 네트워크에 연결을 설정하도록 해 주는 새 멀티 네트워킹 API를 제공합니다. 이 기능은 앱에서 특수한 네트워크(예: SUPL, MMS, 이동통신사 결제 네트워크 또는 특정 유형의 전송 프로토콜을 사용해 데이터를 전송하려는 경우)가 필요할 때 유용합니다.</p>
+
+<p>앱에서 네트워크를 동적으로 선택하고 연결하려면 다음 단계를 따릅니다.</p>
+
+<ol>
+ <li>{@link android.net.ConnectivityManager}를 만듭니다.</li>
+ <li>{@link android.net.NetworkRequest.Builder} 클래스를 사용하여 {@link android.net.NetworkRequest} 개체를 만들고 앱에서 사용하려는 네트워크 기능 및 전송 유형을 지정합니다.</li>
+<li>적합한 네트워크를 스캔하려면 {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} 또는 {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()}을 호출하고 {@link android.net.NetworkRequest} 개체 및 {@link android.net.ConnectivityManager.NetworkCallback} 구현에 전달합니다. 적합한 네트워크가 감지되었을 때 능동적으로 전환하도록 하려면 {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} 메소드를 사용합니다. 능동적인 전환 없이 스캔한 네트워크에 대한 알림만 받으려면 {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()} 메소드를 사용합니다.</li>
+</ol>
+
+<p>시스템에서 적절한 네트워크를 감지하면 감지한 네트워크에 연결하고 {@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()} 콜백을 호출합니다. 콜백의 {@link android.net.Network} 개체를 사용하여 네트워크에 대한 추가 정보를 가져오거나, 트래픽이 선택한 네트워크를 사용하도록 유도합니다.</p>
+
+<h3 id="BluetoothBroadcasting">저전력 블루투스</h3>
+<p>Android 4.3에서는 <a href="{@docRoot}guide/topics/connectivity/bluetooth-le.html">저전력 블루투스</a>(<em>블루투스 LE</em>)에 대한 플랫폼 지원이 도입되었습니다. Android 5.0에서는 Android 기기가 블루투스 LE <em>주변기기</em>로 작동할 수 있습니다. 앱에서 이 기능을 사용하여 주변 기기에 블루투스로 연결할 수 있음을 알릴 수 있습니다. 예를 들어 기기가 만보계나 건강 모니터링 기기로 작동하면서 다른 블루투스 LE 기기와 데이터를 통신할 수 있도록 하는 앱을 제작할 수 있습니다.</p>
+<p>새 {@link android.bluetooth.le} API를 사용하면 앱에서 광고를 브로드캐스팅하고, 응답을 스캔하며, 주변의 블루투스 LE 기기와 연결을 설정하도록 할 수 있습니다. 새 광고 및 스캔 기능을 사용하려면 매니페스트에 {@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN} 권한을 추가합니다. 사용자가 Play 스토어에서 앱을 업데이트하거나 다운로드할 때 사용자에게 앱에 권한을 부여할 것인지 묻는 메시지('블루투스 연결 정보: 주변의 블루투스 기기에 브로드캐스팅하거나 이러한 기기에 대한 정보 수집하는 등 앱에서 블루투스를 제어하도록 허용합니다.')가 표시됩니다.</p>
+
+<p>다른 앱에서 내 앱을 찾을 수 있도록 블루투스 LE 광고를 시작하려면 {@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()}을 호출하고 이를 {@link android.bluetooth.le.AdvertiseCallback} 클래스 구현에 전달합니다. 콜백 개체는 광고 작업의 성공 또는 실패에 대한 보고서를 수신합니다.</p>
+
+<p> Android 5.0에는 {@link android.bluetooth.le.ScanFilter} 클래스가 도입되어 앱에서 연결하려는 특정 유형의 기기만 스캔하도록 할 수 있습니다. 블루투스 LE 기기 스캔을 시작하려면 {@link android.bluetooth.le.BluetoothLeScanner#startScan(android.bluetooth.le.ScanCallback) startScan()}을 호출하고 필터 목록으로 전달합니다. 메소드 호출에서 {@link android.bluetooth.le.ScanCallback} 구현도 제공하여 블루투스 LE 광고를 찾은 시점을 보고해야 합니다. </p>
+
+<h3 id="NFCEnhancements">NFC 개선사항</h3>
+<p>Android 5.0에서는 다음과 같은 개선사항을 통해 더욱 폭넓고 자유롭게 NFC를 사용할 수 있게 되었습니다.</p>
+
+<ul>
+<li>이제 <em>공유</em> 메뉴에서 Android Beam을 사용할 수 있습니다.</li>
+<li>{@link android.nfc.NfcAdapter#invokeBeam(android.app.Activity) invokeBeam()}을 호출하는 방식으로 앱이 사용자의 기기에서 Android Beam을 호출하여 데이터를 공유할 수 있습니다. 이를 통해 사용자가 데이터 전송을 완료하기 위해 기기를 다른 NFC 지원 기기에 직접 탭하지 않아도 됩니다.</li>
+<li>새 {@link android.nfc.NdefRecord#createTextRecord(java.lang.String, java.lang.String) createTextRecord()} 메소드를 사용하여 UTF-8 텍스트 데이터가 포함된 NDEF 기록을 만들 수 있습니다.</li>
+<li>결재 앱을 개발 중인 경우 <code><a href="{@docRoot}reference/android/nfc/cardemulation/CardEmulation.html#registerAidsForService(android.content.ComponentName, java.lang.String, java.util.List<java.lang.String>)">registerAidsForService()</a></code>를 호출하여 NFC AID(애플리케이션 ID)를 동적으로 등록할 수 있습니다. 또한 {@link android.nfc.cardemulation.CardEmulation#setPreferredService(android.app.Activity, android.content.ComponentName) setPreferredService()}를 사용하여 특정 액티비티가 포그라운드에 있을 때 사용되어야 하는 카드 에뮬레이션 서비스를 원하는 대로 설정할 수 있습니다.</li>
+</ul>
+
+<h2 id="Power">프로젝트 Volta</h2>
+
+<p>새 기능과 이외에, Android 5.0에서는 배터리 수명을 개선하는 데 집중하고 있습니다. 새 API 및 도구를 사용하여 앱의 전력 소비를 파악하고 최적화할 수 있습니다.</p>
+
+<h3 id="JobScheduler">작업 예약</h3>
+<p>Android 5.0에서는 시스템에서 나중에 또는 특정 조건(예: 기기가 충전될 때)에서 비동기식으로 실행할 작업을 정의하여 배터리 수명을 최적화할 수 있는 새 {@link android.app.job.JobScheduler} API를 제공합니다. 작업 예약은 다음과 같은 상황에서 유용합니다.</p>
+<ul>
+ <li>앱에 사용자가 확인하지 않아도 되며 연기할 수 있는 작업이 있는 경우</li>
+ <li>앱에 기기가 전원에 연결된 상태에서 수행하려는 작업이 있는 경우</li>
+ <li>앱에 네트워크 액세스 또는 Wi-Fi 연결이 필요한 작업이 있는 경우</li>
+ <li>앱에 정기으로 일괄 실행하려는 여러 작업이 있는 경우</li>
+
+</ul>
+
+<p>작업 단위는 {@link android.app.job.JobInfo} 개체에 의해 캡슐화됩니다. 이 개체는 예약 기준을 지정합니다.</p>
+
+<p>{@link android.app.job.JobInfo.Builder} 클래스를 사용하여 예약된 작업이 실행되어야 하는 방식을 구성합니다. 다음과 같은 특정 조건에서 작업이 실행되도록 예약할 수 있습니다.</p>
+
+<ul>
+ <li>기기가 충전 중일 때 시작</li>
+ <li>기기가 무제한 네트워크에 연결될 때 시작</li>
+ <li>기기가 유휴 상태일 때 시작</li>
+ <li>특정 기한 전에 종료 또는 지연을 최소화하여 종료</li>
+</ul>
+
+<p>예를 들어 다음과 같은 코드를 추가하여 무제한 네트워크에서 작업을 실행할 수 있습니다.</p>
+
+<pre>
+JobInfo uploadTask = new JobInfo.Builder(mJobId,
+ mServiceComponent /* JobService component */)
+ .setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED)
+ .build();
+JobScheduler jobScheduler =
+ (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
+jobScheduler.schedule(uploadTask);
+</pre>
+
+<p>기기가 안정적인 전원에 연결된 경우(즉, 기기가 2분 이상 충전 중이며 배터리가 <a href="{@docRoot}reference/android/content/Intent.html#ACTION_BATTERY_OKAY">충분한 수준</a>인 경우) 시스템에서 작업의 기한이 지나지 않았더라도 실행 준비가 된 예약 작업을 실행합니다.</p>
+
+<p>{@link android.app.job.JobScheduler} API를 사용하는 방법의 예를 확인하려면 이 출시 버전의 {@code JobSchedulerSample} 구현 샘플을 참조하세요.</p>
+
+<h3 id="PowerMeasurementTools">배터리 사용량을 위한 개발자 도구</h3>
+
+<p>새 {@code dumpsys batterystats} 명령은 기기의 배터리 사용량에 대해 흥미로운 통계 데이터를 생성하고, 이러한 데이터는 고유한 UID(사용자 ID)로 정리됩니다. 통계에는 다음이 포함됩니다.</p>
+
+<ul>
+<li>배터리 관련 이벤트 기록
+<li>기기에 대한 전체 통계
+<li>UID 및 시스템 구성요소당 대략적인 전력 사용량
+<li>패킷당 앱별 모바일 ms
+<li>시스템 UID로 집계된 통계
+<li>앱 UID로 집계된 통계
+</ul>
+
+<p>{@code --help} 옵션을 사용하여 통계를 맞춤설정하는 다양한 방법에 대해 알아볼 수 있습니다. 예를 들어 기기가 마지막으로 충전된 이후 특정 앱 패키지에서의 배터리 사용량 통계를 출력하려면 다음 명령을 실행합니다.
+<pre>
+$ adb shell dumpsys batterystats --charged &lt;package-name&gt;
+</pre>
+
+<p>{@code dumpsys} 명령의 출력에서 <a href="https://github.com/google/battery-historian" class="external-link">Battery Historian</a> 도구를 사용하여 로그로부터 전력 관련 이벤트를 가져와 HTML 형식으로 볼 수 있습니다. 이 정보는 배터리 관련 문제를 쉽게 파악하고 진단할 수 있게 해 줍니다.</p>
+
+<h2 id="Enterprise">업무 및 교육을 위한 Android</h2>
+<h3 id="ManagedProvisioning">관리되는 프로비저닝</h3>
+
+<p>Android 5.0에서는 기업 환경에서 사용하는 앱을 위한 새 기능을 제공합니다. 사용자에게 기존 개인 계정이 있는 경우, <a href="{@docRoot}guide/topics/admin/device-admin.html">기기 관리자</a>는 관리되는 프로비저닝 과정을 시작하여 기기에 동시에 존재하지만 분리된 <em>관리되는 프로필</em>을 추가할 수 있습니다. 관리되는 프로필에 연결된 앱은 사용자의 런처, 최근 화면, 알림에서 관리되지 않는 앱과 함께 표시됩니다.</p>
+
+<p>관리되는 프로비저닝 과정을 시작하려면 {@link android.content.Intent}의 {@link android.app.admin.DevicePolicyManager#ACTION_PROVISION_MANAGED_PROFILE ACTION_PROVISION_MANAGED_PROFILE}을 전송합니다. 호출이 성공하면 시스템에서 {@link android.app.admin.DeviceAdminReceiver#onProfileProvisioningComplete(android.content.Context, android.content.Intent) onProfileProvisioningComplete()} 콜백을 실행합니다. 그러면 {@link android.app.admin.DevicePolicyManager#setProfileEnabled(android.content.ComponentName) setProfileEnabled()}를 호출하여 관리되는 프로필을 사용 설정할 수 있습니다.</p>
+
+<p>기본적으로 앱의 일부 하위 집합만 관리되는 프로필에서 사용 설정됩니다. {@link android.app.admin.DevicePolicyManager#enableSystemApp(android.content.ComponentName, android.content.Intent) enableSystemApp()}을 호출하여 관리되는 프로필에서 추가 앱을 설치할 수 있습니다.</p>
+
+<p>런처 앱을 개발 중인 경우 새 {@link android.content.pm.LauncherApps} 클래스를 사용하여 현재 사용자 및 연결된 관리되는 프로필에 대해 실행할 수 있는 액티비티의 목록을 가져올 수 있습니다. 런처에서는 작업 배지를 아이콘 드로어블에 추가하여 관리되는 앱을 눈에 띄게 만들 수 있습니다. 배지 아이콘을 가져오려면 {@link android.content.pm.PackageManager#getUserBadgedIcon(android.graphics.drawable.Drawable, android.os.UserHandle) getUserBadgedIcon()}을 호출합니다.</p>
+
+<p>새 기능을 사용하는 방법을 확인하려면 이 출시 버전의 {@code BasicManagedProfile} 구현 샘플을 참조하세요.</p>
+
+<h3 id="DeviceOwner">기기 소유자</h3>
+<p>Android 5.0에는 기기 소유자 앱을 배포할 수 있는 기능이 도입되었습니다. <em>기기 소유자</em>는 특수한 유형의 <a href="{@docRoot}guide/topics/admin/device-admin.html">기기 관리자</a>로, 보조 사용자를 만들거나 제거하고 기기에서 전체 설정을 구성할 수 있습니다. 기기 소유자 앱에서는 {@link android.app.admin.DevicePolicyManager} 클래스의 메소드를 사용하여 관리되는 기기에서 구성, 보안 및 앱을 세부적으로 제어할 수 있습니다. 기기에는 한 번에 한 명의 활성 기기 소유자만 있어야 합니다.</p>
+
+<p>기기 소유자를 적용하고 활성화하려면 기기가 프로비저닝되지 않은 상태에서, 프로그래밍 앱에서 기기로 NFC 데이터를 전송해야 합니다. 이 데이터 전송 시 <a href="#ManagedProvisioning">관리되는 프로비저닝</a>에서 설명한 프로비저닝 인텐트의 정보와 동일한 정보가 전송됩니다.</p>
+
+<h3 id="ScreenPinning">화면 고정</h3>
+
+<p>Android 5.0에는 새 화면 고정 API가 도입되어 일시적으로 사용자가 작업에서 벗어나거나 알림에 의해 방해받는 것을 제한할 수 있습니다. 예를 들어 이 기능은 Android에서 중대한 평가를 위한 교육용 앱, 용도가 하나로 고정된 애플리케이션이나 키오스크 용 애플리케이션을 개발 중인 경우에 사용할 수 있습니다. 앱에서 화면 고정을 활성화하면 앱에서 고정 모드를 종료할 때까지 사용자는 알림을 보거나 다른 앱에 액세스하거나 홈 화면으로 돌아갈 수 없습니다.</p>
+
+<p>다음과 같은 두 가지 방법으로 화면 고정을 활성화할 수 있습니다.</p>
+
+<ul>
+<li><strong>수동 방식:</strong> 사용자는 <em>설정 &gt; 보안 &gt; 화면 고정</em>으로 이동하여 화면 고정을 사용 설정하고, 최근 화면에서 녹색 핀 아이콘을 터치하여 고정하려는 작업을 선택할 수 있습니다.</li> <li><strong>프로그래밍 방식:</strong> 프로그래밍 방식으로 화면 고정을 활성화하려면 앱에서 {@link android.app.Activity#startLockTask() startLockTask()}를 호출합니다. 요청하는 앱이 기기 소유자가 아닌 경우 사용자에게 확인 메시지가 표시됩니다. 기기 소유자 앱은 {@link android.app.admin.DevicePolicyManager#setLockTaskPackages(android.content.ComponentName, java.lang.String[]) setLockTaskPackages()} 메소드를 호출하여 사용자 확인 단계 없이 앱을 고정 가능하게 설정할 수 있습니다.</li>
+</ul>
+
+<p>작업 잠금이 활성 상태이면 다음 동작이 진행됩니다.</p>
+
+<ul>
+<li>상태 표시줄이 공백으로 표시되고 사용자 알림 및 상태 정보가 숨겨집니다.</li>
+<li>홈 및 최근 앱 버튼이 숨겨집니다.</li>
+<li>다른 앱에서 새 액티비티를 실행할 수 없습니다.</li>
+<li>새 액티비티로 인해 새 작업이 생성되지 않는 이상 현재 앱에서 새 액티비티를 시작할 수 있습니다.</li>
+<li>기기 소유자가 화면 고정을 호출하면 앱에서 {@link android.app.Activity#stopLockTask() stopLockTask()}를 호출할 때까지 사용자의 앱이 잠금 상태로 남아 있습니다.</li>
+<li>화면 고정이 기기 소유자가 아닌 다른 앱 또는 사용자가 직접 수행하는 액티비티인 경우, 사용자는 뒤로 및 최근 버튼을 길게 터치하여 화면 고정을 종료할 수 있습니다.</li>
+
+</ul>
+
+<h2 id="Printing">인쇄 프레임워크</h2>
+
+<h3 id="PDFRender">PDF를 비트맵으로 렌더링</h3>
+<p>이제 새 {@link android.graphics.pdf.PdfRenderer} 클래스를 사용하여 PDF 문서 페이지를 비트맵 이미지로 렌더링하여 인쇄할 수 있습니다. 찾을 수 있는(즉, 콘텐츠에 임의로 액세스할 수 있는) {@link android.os.ParcelFileDescriptor}를 지정해야 합니다. 여기에 시스템에서 인쇄 가능한 콘텐츠를 쓰게 됩니다. 앱에서는 {@link android.graphics.pdf.PdfRenderer#openPage(int) openPage()}를 사용하여 렌더링하려는 페이지를 가져와서 {@link android.graphics.pdf.PdfRenderer.Page#render(android.graphics.Bitmap, android.graphics.Rect, android.graphics.Matrix, int) render()}를 호출하여 열려 있는 {@link android.graphics.pdf.PdfRenderer.Page}를 비트맵으로 전환할 수 있습니다. 문서 일부만 비트맵 이미지로 전환하려는 경우 추가 매개변수를 설정할 수도 있습니다(예: 문서에서 확대하기 위해 <a href="http://en.wikipedia.org/wiki/Tiled_rendering" class="external-link">타일식 렌더링</a>을 구현하려는 경우).</p>
+
+<p>새 API를 사용하는 방법에 대한 예는 {@code PdfRendererBasic} 샘플을 참조하세요.</p>
+
+<h2 id="System">시스템</h2>
+<h3 id="AppUsageStatistics">앱 사용량 통계</h3>
+<p>새 {@link android.app.usage} API를 사용하여 Android 기기에서 앱 사용량 기록에 액세스할 수 있습니다. 이 API는 사용 중지된 {@link android.app.ActivityManager#getRecentTasks(int, int) getRecentTasks()} 메소드보다 더 자세한 사용량 정보를 제공합니다. 이 API를 사용하려면 먼저 매니페스트에서 {@code "android.permission.PACKAGE_USAGE_STATS"} 권한을 선언해야 합니다. 또한 사용자는 <em>설정 &gt; 보안 &gt; 앱</em>에서 사용량 액세스와 함께 해당 앱에 대한 액세스를 사용 설정해야 합니다.</p>
+
+<p>시스템에서는 앱 단위 사용량 데이터를 수집하며 일일, 주간, 월간 및 연간 단위로 데이터를 집계합니다. 시스템에서 이 데이터를 보관하는 최대 기간은 다음과 같습니다.</p>
+
+<ul>
+ <li>일일 데이터: 7일</li>
+ <li>주간 데이터: 4주</li>
+ <li>월간 데이터: 6개월</li>
+ <li>연간 데이터: 2년</li>
+</ul>
+
+<p>각 앱에 대해 시스템에서는 다음 데이터를 기록합니다.</p>
+<ul>
+<li>앱이 마지막으로 사용된 시간</li>
+<li>해당 기간(일, 주, 월 또는 연도별)에 앱이 포그라운드에서 작동한 총 시간</li>
+<li>구성요소(패키지 및 액티비티 이름으로 식별)가 하루 동안 포그라운드 또는 백그라운드로 이동한 시기를 캡처한 타임스탬프</li>
+<li>기기 구성이 변경된 시점(예: 회전으로 인해 기기 방향이 변경된 시점)을 캡처한 타임스탬프</li>
+</ul>
+
+<h2 id="TestingA11y">테스트 및 접근성 </h2>
+
+<h3 id="TestingA11yImprovements">테스트 및 접근성 개선사항</h3>
+<p>Android 5.0에는 다음과 같은 테스트 및 접근성 지원이 추가되었습니다.</p>
+
+<ul>
+<li>새 {@link android.app.UiAutomation#getWindowAnimationFrameStats() getWindowAnimationFrameStats()} 및 {@link android.app.UiAutomation#getWindowContentFrameStats(int) getWindowContentFrameStats()} 메소드는 창 애니메이션 및 콘텐츠에 대한 프레임 통계를 캡처합니다. 이러한 메소드를 사용하면 차질 없는 사용자 경험을 제공하기 위해 앱에서 충분한 새로고침 빈도로 프레임을 렌더링하는지 평가할 수 있는 작동 테스트를 작성할 수 있습니다.</li>
+
+<li>새 {@link android.app.UiAutomation#executeShellCommand(java.lang.String) executeShellCommand()} 메소드를 사용하면 작동 테스트에서 셸 명령을 실행할 수 있습니다. 명령 실행은 기기에 연결된 호스트에서 {@code adb shell}을 실행하는 것과 비슷하며, 실행하면 {@code dumpsys}, {@code am}, {@code content} 및 {@code pm}와 같은 셸 기반 도구를 사용할 수 있게 됩니다.</li>
+
+<li>이제 접근성 API(예: <a href="{@docRoot}tools/help/uiautomator/index.html">{@code UiAutomator}</a>)를 사용하는 접근성 서비스 및 테스트 도구에서 일반 사용자가 상호작용할 수 있는 화면의 창 속성에 대한 자세한 정보를 가져올 수 있습니다. {@link android.view.accessibility.AccessibilityWindowInfo} 개체 목록을 가져오려면 새 {@link android.accessibilityservice.AccessibilityService#getWindows() getWindows()} 메소드를 호출합니다.</li>
+
+<li>새 {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} 클래스를 사용하면 {@link android.view.accessibility.AccessibilityNodeInfo}에서 수행할 표준 또는 맞춤 작업을 정의할 수 있습니다. 새 {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} 클래스는 이전에 {@link android.view.accessibility.AccessibilityNodeInfo}에서 찾을 수 있던 작업 관련 API를 대체합니다.</li>
+
+<li>Android 5.0에서는 앱에서 TTS(텍스트 음성 변환) 합성을 세부적으로 제어할 수 있습니다. 새 {@link android.speech.tts.Voice} 클래스를 사용하면 앱에서 특정 언어에 연결된 음성 프로필, 품질과 지연 시간 평가 및 TTS(텍스트 음성 변환) 엔진 전용 매개변수를 사용할 수 있습니다.</li>
+</ul>
+
+<h2 id="IME">IME</h2>
+
+<h3 id="Switching">더 쉽게 입력 언어를 전환</h3>
+
+<p>Android 5.0부터 사용자는 플랫폼에서 지원하는 모든 <a href="{@docRoot}guide/topics/text/creating-input-method.html">IME(입력 방법 편집기)</a> 간에 더 쉽게 전환할 수 있습니다. 지정된 전환 작업(보통 소프트웨어 키보드에서 지구 아이콘을 터치)을 수행하면 이러한 모든 IME가 순환 적용됩니다. 이러한 작동 변경사항은 {@link android.view.inputmethod.InputMethodManager#shouldOfferSwitchingToNextInputMethod(android.os.IBinder) shouldOfferSwitchingToNextInputMethod()} 메소드에 의해 구현되었습니다.</p>
+
+<p>또한 이제 프레임워크에서 다음 IME에 전환 메커니즘이 포함되어 있는지, 즉 다음 IME가 그 다음 IME로의 전환을 지원하는지 확인합니다. 전환 메커니즘이 있는 IME는 메커니즘이 없는 IME로 순환 이동하지 않습니다. 이러한 작동 변경사항은 {@link android.view.inputmethod.InputMethodManager#switchToNextInputMethod(android.os.IBinder, boolean) switchToNextInputMethod()} 메소드에 의해 구현되었습니다.
+
+<p>업데이트된 IME 전환 API를 사용하는 방법에 대한 예를 확인하려면 이 출시 버전의 업데이트된 소프트웨어 키보드 구현 샘플을 참조하세요. IME 간에 전환을 구현하는 방법에 대해 자세히 알아보려면 <a href="{@docRoot}guide/topics/text/creating-input-method.html">입력 방법 만들기</a>를 참조하세요.
+</p>
+
+<h2 id="Manifest">매니페스트 선언</h2>
+
+<h3 id="ManifestFeatures">선언 가능한 필수 기능</h3>
+<p>이제 다음 값이 <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> 요소에서 지원되므로, 앱에서 필요한 기능을 제공하는 기기에만 앱이 설치됩니다.</p>
+
+<ul>
+<li>{@link android.content.pm.PackageManager#FEATURE_AUDIO_OUTPUT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_POST_PROCESSING}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_SENSOR}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_RAW}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_LEVEL_FULL}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_GAMEPAD}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LIVE_TV}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_MANAGED_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LEANBACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_OPENGLES_EXTENSION_PACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SECURELY_REMOVES_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_AMBIENT_TEMPERATURE}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_HEART_RATE_ECG}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_RELATIVE_HUMIDITY}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_VERIFIED_BOOT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_WEBVIEW}</li>
+</ul>
+
+<h3 id="Permissions">사용자 권한</h3>
+
+<p>이제 다음 권한이 <a href="{@docRoot}guide/topics/manifest/uses-permission-element.html">{@code <uses-permission>}</a> 요소에서 지원되어 앱이 특정 API에 액세스하는 데 필요한 권한을 선언할 수 있습니다.</p>
+
+<ul>
+<li>{@link android.Manifest.permission#BIND_DREAM_SERVICE}: API 수준 21 이상을 타겟팅하는 경우, 시스템만 <a href="{@docRoot}about/versions/android-4.2.html#Daydream">Daydream</a> 서비스에 결합할 수 있는지 확인하기 위해 Daydream 서비스에서 이 권한을 요구합니다.</li>
+</ul>
diff --git a/docs/html-intl/intl/ko/about/versions/lollipop.jd b/docs/html-intl/intl/ko/about/versions/lollipop.jd
new file mode 100644
index 0000000..f6f292a
--- /dev/null
+++ b/docs/html-intl/intl/ko/about/versions/lollipop.jd
@@ -0,0 +1,246 @@
+page.title=Android Lollipop
+
+@jd:body
+
+
+ <div style="padding:0px 0px 0px 20px;float:right;margin:0 -10px 0 0">
+ <img src="{@docRoot}images/home/l-hero_2x.png" srcset="{@docRoot}images/home/l-hero.png 1x, {@docRoot}images/home/l-hero_2x.png 2x" width="460" height="300" >
+ </div>
+
+ <div class="landing-docs" style="float:right;clear:both;margin:68px 0 2em 3em;">
+ <div class="col-4 normal-links highlights" style="font-size:12px;">
+ <h3 id="thisd" >핵심 개발자 기능</h3>
+ <ul style="list-style-type:none;">
+ <li><a href="#Material">머티리얼 디자인</a></li>
+ <li><a href="#Perf">성능 중심</a></li>
+ <li><a href="#Notifications">알림</a></li>
+ <li><a href="#TV">큰 화면에서 앱 표시</a></li>
+ <li><a href="#Documents">문서 중심 앱</a></li>
+ <li><a href="#Connectivity">향상된 연결</a></li>
+ <li><a href="#Graphics">고성능 그래픽</a></li>
+ <li><a href="#Audio">더 강력해진 오디오</a></li>
+ <li><a href="#Camera">개선된 카메라 및 동영상</a></li>
+ <li><a href="#Work">업무를 위한 Android</a></li>
+ <li><a href="#ScreenCapture">화면 캡처 및 공유</a></li>
+ <li><a href="#Sensors">새로운 유형의 센서</a></li>
+ <li><a href="#WebView">Chromium WebView</a></li>
+ <li><a href="#Accessibility">접근성 및 입력</a></li>
+ <li><a href="#Battery">배터리를 효율적으로 사용하는 앱을 위한 도구</a></li>
+ </ul>
+ </div>
+</div>
+
+
+
+
+
+
+
+<p>지금까지의 Android 출시 버전 중 가장 크고 야심 차게 준비한 Android 5.0 Lollipop을 소개합니다.</p>
+
+<p>이번 출시 버전에는 사용자를 위한 새로운 기능과 개발자를 위한 수천 가지의 새로운 API가 포함되어 있습니다. 이제 Android를 휴대전화, 태블릿, 웨어러블 기기뿐만 아니라 TV와 자동차에서도 사용할 수 있습니다.</p>
+
+<p>새로운 개발자 API에 대해 자세히 살펴보려면 <a href="{@docRoot}about/versions/android-5.0.html">Android 5.0 API 개요</a>를 참조하세요. 또는 <a href="http://www.android.com/versions/lollipop-5-0/">www.android.com</a>에서 소비자를 위한 Android 5.0에 대해 자세히 읽어 볼 수 있습니다.</p>
+
+<h2 id="Material">머티리얼 디자인</h2>
+
+<p>Android 5.0에서는 Android에 <a href="http://www.google.com/design/spec">머티리얼 디자인</a>을 도입하여 새로운 디자인 패턴을 앱과 간편하게 통합할 수 있는 확장된 UI 툴킷을 제공합니다. </p>
+
+
+
+<p>새로운 <strong>3D 보기</strong>를 사용하면 z-레벨을 설정하여 보기 계층구조에서 요소가 위에 나타나도록 하고, 움직이는 동안에도 <strong>실시간 그림자</strong>가 표시되도록 할 수 있습니다.</p>
+
+
+<p>내장된 <strong>액티비티 전환</strong>은 아름다운 애니메이션 모션을 제공해 사용자가 다른 상태로 원활하게 전환할 수 있게 해 줍니다. 머티리얼 테마는 액티비티 간 <strong>공유된 시각적 요소</strong>를 사용할 수 있는 기능을 포함하여, 액티비티에 전환을 추가해 줍니다.</p>
+
+
+
+<div style="width:290px;margin-right:35px;float:left">
+ <div class="framed-nexus5-port-span-5">
+ <video class="play-on-hover" autoplay="">
+ <source src="/design/material/videos/ContactsAnim.mp4">
+ <source src="/design/videos/ContactsAnim.webm">
+ <source src="/design/videos/ContactsAnim.ogv">
+ </video>
+ </div>
+ <div style="font-size:10pt;margin-left:20px;margin-bottom:30px">
+ <em>영화를 다시 재생하려면 기기 화면을 클릭하기만 하면 됩니다</em>
+ </div>
+</div>
+
+
+<p>물결 애니메이션을 앱의 버튼, 체크박스, 기타 터치 컨트롤에 사용할 수 있습니다.
+
+<p>또한 XML에서 벡터 드로어블을 정의하고 다양한 방법으로 애니메이션을 적용할 수도 있습니다. 벡터 드로어블은 정의 값을 잃지 않고 크기가 조절되므로 단일 색상 인앱 아이콘에 적합합니다.</p>
+
+<p><strong>RenderThread</strong>라고 하는 시스템에서 관리되는 새 처리 스레드를 통해 기본 UI 스레드에 지연이 발생하더라도 애니메이션을 부드럽게 유지해 줍니다. </p>
+
+
+<h2 id="Perf">성능 중심</h2>
+
+<p>Android 5.0은 더 빠르고 매끄럽고 강력해진 컴퓨팅 환경을 제공합니다.</p>
+
+<p>Android는 이제 새로운 <strong>ART 런타임</strong>에서만 실행되며, 이 런타임은 AOT(ahead-of-time), JIT(just-in-time) 및 해석된 코드의 조합을 지원하도록 처음부터 다시 제작되었습니다. ARM, x86 및 MIPS 아키텍처에서 지원되며 64비트에서 완벽하게 호환됩니다.</p>
+
+<p>ART는 앱 성능과 반응성을 개선해 줍니다. 효율적인 가비지 컬렉션이 GC 이벤트의 일시중지 횟수와 시간을 감소시켜 주므로, v-동기화 창 내에 쉽게 배치되어 앱이 프레임을 건너뛰지 않게 합니다. 또한 ART는 메모리를 동적으로 이동하여 포그라운드에서 사용되는 앱을 위해 성능을 최적화합니다. </p>
+
+<p>Android 5.0에서는 Nexus 9의 NVIDIA Tegra K1에서 사용하는 <strong>64비트 아키텍처</strong>에 대한 플랫폼 지원을 도입했습니다. 최적화를 통해 더 큰 주소 공간을 제공하고 특정 컴퓨팅 작업을 위한 성능을 개선했습니다. 자바 언어로 쓰인 앱은 64비트 앱으로 자동 실행되므로 수정이 필요하지 않습니다. 앱에서 기본 코드를 사용하는 경우를 위해 ARM v8, x86~64 및 MIPS-64용 새 ABI를 지원하도록 NDK를 확장했습니다.</p>
+
+<p>더 매끄러운 성능을 위한 노력은 여기서 그치지 않고 Android 5.0에서는 향상된 A/V 동기화를 제공합니다. 오디오 및 그래픽 파이프라인이 더 정확한 타임스탬프가 가능하도록 제작되어 동영상 앱과 게임에서 자연스럽게 동기화된 콘텐츠를 표시할 수 있습니다.</p>
+
+
+<h2 id="Notifications">알림</h2>
+
+<p>Android 5.0의 알림은 표시, 액세스 및 구성이 더욱 편리해 졌습니다. </p>
+
+<img src="{@docRoot}images/versions/notification-headsup.png" style="float:right; margin:0 0 40px 60px" width="300" height="224" />
+
+<p>사용자가 원하는 경우 <strong>잠금 화면</strong>에 다양한 세부정보 수준을 지정해 알림을 표시할 수 있습니다. 사용자는 보안 잠금 화면에 알림 내용을 모두 표시할지, 일부만 표시할지, 전혀 표시하지 않을지를 선택할 수 있습니다. </p>
+
+<p>수신 전화와 같은 주요 알림은 사용자가 현재 사용 중인 앱을 벗어나지 않고 응답하거나 닫을 수 있는 작은 플로팅 창인 <strong>헤드업 알림</strong>에 표시됩니다.</p>
+
+<p>이제 알림에 <strong>새 메타데이터</strong>를 추가하여 관련 연락처(순위 지정 용), 카테고리, 우선순위를 수집할 수 있습니다.</p>
+
+<p>새 미디어 알림 템플릿에서는 '좋아요'와 같은 맞춤 컨트롤을 비롯하여 최대 6개의 액션 버튼으로 알림에 일관된 미디어 컨트롤을 제공하므로, 더 이상 RemoteView가 필요하지 않습니다.</p>
+
+
+
+<h2 id="TV">큰 화면에서 앱 표시</h2>
+
+<p><a href="http://developer.android.com/tv/index.html">Android TV</a>에서는 앱을 TV 화면으로 경험할 수 있도록 하는 완벽한 TV 플랫폼을 제공합니다. Android TV는 사용자가 맞춤 추천과 음성 검색을 통해 콘텐츠를 편리하게 찾을 수 있게 해 주는 간편한 홈 스크린 경험을 중심으로 제작되었습니다.</p>
+
+<p>Android TV를 사용하면 사용자가 앱이나 게임 콘텐츠를 <strong>생생하게 경험</strong>하도록 할 수 있으며, 게임 컨트롤러 및 기타 입력 기기와의 상호작용을 지원할 수 있습니다. 텔레비전용 3미터 크기 UI를 생생하게 제작할 수 있도록 Android는 <strong>린백 UI 프레임워크</strong>를 <a href="{@docRoot}tools/support-library/features.html#v17-leanback">v17 지원 라이브러리</a>에서 제공합니다.</p>
+
+<p><strong>Android TIF(TV 입력 프레임워크)</strong>를 사용하면 TV 앱이 HDMI 입력, TV 튜너 및 IPTV 수신기와 같은 소스로부터 동영상 스트림을 처리할 수 있습니다. 또한 TV 입력에서 게시한 메타데이터를 통해 실시간 TV 검색과 추천을 사용할 수 있으며, 하나의 리모컨으로 여러 기기를 조작할 수 있는 HDMI-CEC 컨트롤 서비스도 포함되어 있습니다. </p>
+
+<p>TV 입력 프레임워크는 다양한 실시간 TV 입력 소스를 사용할 수 있게 해 주며, 이를 단일 사용자 인터페이스로 통합하여 사용자가 콘텐츠를 탐색하고 보고 즐길 수 있게 해 줍니다. 콘텐츠에 TV 입력 서비스를 구축하면 TV 기기에서 콘텐츠를 더욱 쉽게 액세스할 수 있습니다.</p>
+
+
+
+<img src="{@docRoot}images/versions/recents_screen_2x.png" srcset="{@docRoot}images/versions/recents_screen.png 1x, {@docRoot}images/versions/recents_screen_2x.png 2x" style="float:right; margin:0 0 40px 60px" width="300" height="521" />
+
+<h2 id="Documents">문서 중심 앱</h2>
+
+<p>Android 5.0에서는 새로 디자인된 '개요' 공간(이전에는 '최근')을 통해 더 다양하고 유용한 멀티태스킹이 가능해 졌습니다.</p>
+
+<p>새 API를 사용하면 앱에서 수행되는 별도의 액티비티를 기타 최근 화면과 함께 개별 문서로 표시할 수 있습니다.</p>
+
+<p>동시 문서를 활용하여 사용자가 더 많은 콘텐츠나 서비스에 즉시 액세스할 수 있도록 할 수 있습니다. 예를 들어 동시 문서를 사용하여 생산성 앱에서는 파일을, 게임에서는 플레이어 대전을, 메시지 앱에서는 채팅을 표시할 수 있습니다. </p>
+
+
+
+<h2 id="Connectivity">향상된 연결</h2>
+
+<p>Android 5.0에서는 앱이 <strong>BLE(저전력 블루투스)</strong>로 동시 작업을 수행할 수 있도록 하는 새 API가 추가되어 스캐닝(중앙 모드)과 광고(주변 모드)가 모두 가능합니다.</p>
+
+<p>새로운 <strong>멀티 네트워크</strong> 기능을 사용하면 앱에서 접속 가능한 네트워크에 어떤 기능이 있는지 쿼리를 보낼 수 있습니다(예: Wi-Fi, 셀룰러, 종량제를 사용하거나 특정 네트워크 기능을 제공하는지). 그런 다음 앱에서 연결을 요청하고 연결 손실 또는 기타 네트워크 변경사항에 반응할 수 있습니다.</p>
+
+<p>이제 <strong>NFC</strong> API를 사용하면 앱에서 NFC AID(애플리케이션 ID)를 동적으로 등록할 수 있습니다. 또한 활성 서비스별로 선호하는 카드 에뮬레이션을 설정하고 UTF-8 텍스트 데이터를 포함한 NDEF 기록을 만들 수도 있습니다.</p>
+
+
+
+<h2 id="Graphics">고성능 그래픽</h2>
+
+<p>이제 <strong><a href="http://www.khronos.org/opengles/3_X/">Khronos OpenGL ES 3.1</a></strong>을 지원하므로, 지원되는 기기에서 게임 및 기타 앱에 최고 성능의 2D 및 3D 그래픽 기능을 제공할 수 있습니다 </p>
+
+<p>OpenGL ES 3.1에서는 컴퓨팅 셰이더, 스텐실 텍스처, 가속 시각 효과, 고품질 ETC2/EAC 텍스처 압축, 고급 텍스처 렌더링, 표준 텍스처 크기 및 렌더 버퍼 포맷 등을 추가합니다.</p>
+
+
+<div class="figure" style="width:350px; margin:0 0 0 60px">
+<img src="{@docRoot}images/versions/rivalknights.png" style="float:right;" width="350" height="525" />
+<p class="img-caption">Gameloft의 Rival Knights는 AEP의 ASTC(Adaptive Scalable Texture Compression) 및 ES 3.1의 컴퓨팅 셰이더를 사용하여 HDR(고 명암비) 블룸 효과와 더 세밀한 그래픽을 제공하고 있습니다.</p>
+</div>
+
+<p>또한 Android 5.0에서는 테셀레이션 셰이더, 도형 셰이더, ASTC 텍스처 압축, 샘플당 보간과 음영 및 기타 고급 렌더링 기능에 액세스할 수 있게 해 주는 OpenGL ES 확장 프로그램 모음인 <strong>AEP(Android 확장 팩)</strong>를 도입했습니다. AEP를 사용하면 다양한 GPU에서 고성능 그래픽을 제공할 수 있습니다.</p>
+
+
+<h2 id="Audio">더 강력해진 오디오</h2>
+
+<p>새로운 오디오 캡처 디자인은 <strong>지연 시간이 단축된 오디오 입력</strong>을 제공합니다. 새로운 디자인에는 읽는 동안을 제외하고는 차단하지 않는 빠른 캡처 스레드와 기본 샘플링 속도, 채널 수 및 비트 심도에서 작동하는 빠른 트랙 캡처 클라이언트가 포함되어 있습니다. 또한 일반 캡처 클라이언트에서 리샘플링, 위/아래 채널 믹스 및 위/아래 비트 심도를 제공합니다.</p>
+
+<p>다중 채널 <strong>오디오 스트림 믹싱</strong>은 전문 오디오 앱에서 5.1 및 7.1 채널을 포함하여 최대 8개의 채널을 믹싱할 수 있게 합니다.</p>
+
+<p>앱에서 미디어 콘텐츠를 노출할 수 있으며 다른 앱의 <strong>미디어를 탐색</strong>한 다음 재생을 요청할 수 있습니다. 콘텐츠는 쿼리 가능한 인터페이스를 통해 노출되며 기기에 저장하지 않아도 됩니다.</p>
+
+<p>앱에서는 특정 언어, 품질 및 지연 속도로 설정된 음성 프로필을 통해 <strong>TTS(텍스트 음성 변환) 합성</strong>을 세밀하게 제어할 수 있습니다. 또한 새 API에서는 합성 오류 확인, 네트워크 합성, 언어 검색, 대체 네트워크에 대한 지원이 개선되었습니다.</p>
+
+<p>이제 Android에서 표준 <strong>USB 오디오</strong> 주변기기를 지원하므로 사용자가 USB 헤드셋, 스피커, 마이크 또는 고품질 디지털 주변기기를 연결할 수 있습니다. 또한 Android 5.0에서는 <strong>Opus</strong> 오디오 코덱 지원도 추가되었습니다.</p>
+
+<p>미디어 재생을 제어하기 위한 새 <strong>{@link android.media.session.MediaSession}</strong> API를 통해 여러 화면과 컨트롤러에서 일관된 미디어 컨트롤을 더욱 간편하게 제공할 수 있습니다.</p>
+
+
+<h2 id="Camera">개선된 카메라 및 동영상</h2>
+
+<p>Android 5.0은 <strong>완전히 새로운 카메라 API</strong>를 도입하여 YUV 및 Bayer RAW와 같은 RAW 포맷을 캡처하고 노출 시간, ISO 감도, 프레임 단위당 프레임 시간과 같은 매개변수를 제어할 수 있습니다. 완전히 동기화된 새 카메라 파이프라인을 사용하면 지원되는 기기에서 압축되지 않은 전체 해상도 YUV 이미지를 30FPS로 캡처할 수 있습니다.</p>
+
+<p>이미지와 함께 카메라의 노이즈 모델 및 광학 정보와 같은 메타데이터를 캡처할 수도 있습니다.</p>
+
+<p>앱에서 네트워크를 통해 동영상 스트림을 전송하는 데 이제 H.265 <strong>HEVC(고효율 동영상 코딩)</strong>를 사용할 수 있어 동영상 데이터 인코딩 및 디코딩이 최적화되었습니다. </p>
+
+<p>또한 Android 5.0에 <strong>멀티미디어 터널링</strong>에 대한 지원이 추가되여 최상의 초 고화질(4K) 콘텐츠 경험을 누리고 압축된 오디오 및 동영상 데이터를 함께 재생할 수 있습니다. </p>
+
+
+
+<div class="figure" style="width:320px; margin:1em 0 0 20px;padding-left:2em;">
+<img style="float:right; margin:0 1em 1em 2em" src="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png" srcset="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png 2x" alt="" width="300" />
+<p class="img-caption">사용자는 개인 및 작업 앱을 통합된 보기에서 확인할 수 있으며 배지로 쉽게 식별할 수 있습니다.</p>
+</div>
+
+
+<h2 id="Work">업무를 위한 Android</h2>
+
+<p>기업 환경에서 bring-your-own-device(업무 용으로 개인 기기 사용)를 시행할 수 있게 새로운 <a href="{@docRoot}about/versions/android-5.0.html#Enterprise">관리되는 프로비저닝 과정</a>에서 기기에 보안 작업 프로필을 생성합니다. 런처에서 작업 배지가 표시된 앱은 앱 및 관련 데이터가 IT 관리자에 의해 작업 프로필 내부에서 관리됨을 나타냅니다.</p>
+
+<p>개인 및 작업 프로필 모두 통합된 보기에 표시됩니다. 각 프로필의 데이터는 두 프로필에서 동일한 앱을 모두 사용하는 경우에도 상대 프로필의 데이터와는 별도로 안전하게 유지됩니다.</p>
+
+<p>회사 소유의 기기의 경우 IT 관리자가 새 기기를 시작하여 <a href="{@docRoot}about/versions/android-5.0.html#DeviceOwner">기기 소유자</a>와 함께 기기를 구성할 수 있습니다. 고용주는 전체 기기 설정을 구성할 수 있도록 기기 소유자 앱이 이미 설치된 기기를 제공할 수 있습니다.</p>
+
+
+
+<h2 id="ScreenCapture">화면 캡처 및 공유</h2>
+
+<p>Android 5.0을 사용하면 앱에 화면 캡처 및 화면 공유 기능을 추가할 수 있습니다. </p>
+
+<p>사용자 권한이 있는 경우 디스플레이에서 비보안 동영상을 캡처하고 원하는 경우 네트워크를 통해 전달할 수 있습니다.</p>
+
+
+<h2 id="Sensors">새로운 유형의 센서</h2>
+
+<p>Android 5.0에서는 새로운 <strong>기울이기 감지기</strong> 센서를 통해 지원되는 기기에서 활동 인식이 개선되었고, <strong>심박수 센서</strong>가 기기를 터치하는 사람의 심박수를 보고합니다. </p>
+
+<p>새로운 <strong>상호작용 복합 센서</strong>는 이제 <em>깨우기</em> 동작, <em>들기</em> 동작 및 <em>보기</em> 동작과 같은 특수한 상호작용을 감지할 수 있습니다.</p>
+
+
+
+<h2 id="WebView">Chromium WebView</h2>
+
+<div style="float:right;margin:1em 2em 1em 2em;">
+ <img src="/images/kk-chromium-icon.png" alt="" height="160" style="margin-bottom:0em;">
+</div>
+
+<p>Android 5.0의 초기 출시 버전에는 Chromium M37 출시 버전을 기반으로 한 {@link android.webkit.WebView}의 Chromium 버전이 포함되며, <strong>WebRTC</strong>, <strong>WebAudio</strong> 및 <strong>WebGL</strong>에 대한 지원이 추가되었습니다. </p>
+
+<p>Chromium M37은 또한 모든 <strong>웹 구성요소</strong> 사양(맞춤 요소, 그림자 DOM, HTML 가져오기 및 템플릿)을 기본으로 지원합니다. 따라서 폴리필 없이도 WebView에서 <a href="http://polymer-project.org/">Polymer</a>와 관련 <a href="https://www.polymer-project.org/docs/elements/material.html">머티리얼 디자인 요소</a>를 사용할 수 있습니다.</p>
+
+<p>Android 4.4 이후로 WebView가 Chromium을 기반으로 해왔지만 이제 Chromium 레이어는 Google Play에서 업데이트할 수 있습니다.</p>
+
+<p>새로운 버전의 Chromium을 사용할 수 있게 되면서 사용자는 Google Play에서 업데이트하여 WebView의 최신 개선사항 및 버그 수정을 적용할 수 있으며, Android 5.0 이상에서 WebView를 사용하는 앱에도 최신 웹 API와 버그 수정을 적용할 수 있습니다.</p>
+
+
+
+<h2 id="Accessibility">접근성 및 입력</h2>
+
+<p>새로운 접근성 API는 일반 사용자가 상호작용할 수 있는 화면의 창 속성에 대한 세부정보를 가져오고 UI 요소에 대한 표준 또는 맞춤 입력 작업을 정의할 수 있습니다.</p>
+
+<p>새로운 IME(입력 방법 편집기) API는 한 입력 방법에서 다른 IME로 직접 빠르게 전환할 수 있게 해 줍니다.</p>
+
+
+
+<h2 id="Battery">배터리를 효율적으로 사용하는 앱을 위한 도구</h2>
+
+<p>새로운 <strong>작업 예약</strong> API를 사용하면 시스템에서 작업을 나중에 수행하도록 연기하거나, 기기 충전 중 또는 Wi-Fi 연결 시와 같은 특정 조건에서 수행되도록 하여 배터리 수명을 최적화할 수 있습니다.</p>
+
+<p>새로운 <code>dumpsys batterystats</code> 명령은 <strong>배터리 사용량 통계</strong>를 생성하여 시스템 단위의 전원 사용량과 앱이 기기 배터리를 사용하는 정도를 파악할 수 있습니다. 전원 이벤트 기록, UID 및 시스템 구성요소당 대략적인 전원 사용량 등을 확인할 수 있습니다.</p>
+
+<img src="{@docRoot}images/versions/battery_historian.png" srcset="{@docRoot}images/versions/battery_historian@2x.png 2x" alt="" width="760" height="462" />
+<p class="img-caption">Battery Historian은 <code>dumpsys batterystats</code>의 통계를 배터리 관련 디버깅을 위한 시각화 자료로 전환해주는 새로운 도구로서, <a href="https://github.com/google/battery-historian">https://github.com/google/battery-historian</a>에서 확인할 수 있습니다.</p>
diff --git a/docs/html-intl/intl/pt-br/about/versions/android-5.0.jd b/docs/html-intl/intl/pt-br/about/versions/android-5.0.jd
new file mode 100644
index 0000000..23904b3
--- /dev/null
+++ b/docs/html-intl/intl/pt-br/about/versions/android-5.0.jd
@@ -0,0 +1,633 @@
+page.title=APIs do Android 5.0
+excludeFromSuggestions=true
+sdk.platform.version=5.0
+sdk.platform.apiLevel=21
+@jd:body
+
+
+<div id="qv-wrapper">
+<div id="qv">
+
+<h2>Neste documento <a href="#" onclick="hideNestedItems('#toc44',this);return false;" class="header-toggle"> <span class="more">mostrar mais</span> <span class="less" style="display:none">mostrar menos</span></a></h2>
+
+<ol id="toc44" class="hide-nested">
+ <li><a href="#ApiLevel">Atualizar seu nível de API desejado</a></li>
+ <li><a href="#Behaviors">Alterações importantes de comportamento</a>
+ <ol>
+ <li><a href="#ART">Caso você ainda não tenha testado seu app no novo tempo de execução do Android (ART)…</a></li>
+ <li><a href="#BehaviorNotifications">Caso seu app implemente notificações…</a></li>
+ <li><a href="#BehaviorMediaControl">Caso seu app use RemoteControlClient…</a></li>
+<li><a href="#BehaviorGetRecentTasks">Caso seu app use getRecentTasks()…</a></li>
+<li><a href="#64BitSupport">Caso você esteja usando o Kit de desenvolvimento nativo do Android (NDK, na sigla em inglês)…</a></li>
+<li><a href="#BindService">Caso seu app esteja associado a um serviço…</a></li>
+<li><a href="#BehaviorWebView">Caso seu app use WebView…</a></li>
+ </ol>
+ </li>
+ <li><a href="#UI">Interface do usuário</a>
+ <ol>
+ <li><a href="#MaterialDesign">Suporte ao material design</a></li>
+ <li><a href="#Recents">Documentos simultâneos recentes e atividades na tela de recentes</a></li>
+ <li><a href="#WebView">Atualizações de WebView</a></li>
+ <li><a href="#ScreenCapture">Compartilhamento e captura de tela</a></li>
+ </ol>
+ </li>
+ <li><a href="#Notifications">Notificações</a>
+ <ol>
+ <li><a href="#LockscreenNotifications">Notificações na tela bloqueada</a></li>
+ <li><a href="#NotificationsMetadata">Metadados de notificações</a></li>
+ </ol>
+ </li>
+ <li><a href="#Graphics">Gráficos</a>
+ <ol>
+ <li><a href="#OpenGLES-3-1">Suporte para OpenGL ES 3.1 </a></li>
+ <li><a href="#AndroidExtensionPack">Pacote de extensões para Android</a></li>
+ </ol>
+ </li>
+ <li><a href="#Media">Mídia</a>
+ <ol>
+ <li><a href="#Camera-v2">API de câmera para funcionalidades avançadas da câmera</a></li>
+ <li><a href="#AudioPlayback">Reprodução de áudio</a></li>
+ <li><a href="#MediaPlaybackControl">Controle de reprodução de mídia</a></li>
+ <li><a href="#MediaBrowsing">Navegação de mídia</a></li>
+ </ol>
+ </li>
+ <li><a href="#Storage">Armazenamento</a>
+ <ol>
+ <li><a href="#DirectorySelection">Seleção do diretório</a></li>
+ </ol>
+ </li>
+ <li><a href="#Wireless">Sem fio e conectividade</a>
+ <ol>
+ <li><a href="#Multinetwork">Várias conexões de rede</a></li>
+ <li><a href="#BluetoothBroadcasting">Transmissão por Bluetooth</a></li>
+ <li><a href="#NFCEnhancements">Aprimoramentos na NFC</a></li>
+ </ol>
+ </li>
+ <li><a href="#Power">Project Volta</a>
+ <ol>
+ <li><a href="#JobScheduler">Agendamento de tarefas</a></li>
+ <li><a href="#PowerMeasurementTools">Ferramentas do desenvolvedor para uso da bateria</a>
+ </ol>
+ </li>
+ <li><a href="#Enterprise">Android no local de trabalho e na educação</a>
+ <ol>
+ <li><a href="#ManagedProvisioning">Aprovisionamento gerenciado</a></li>
+ <li><a href="#DeviceOwner">Proprietário do dispositivo</a></li>
+ <li><a href="#ScreenPinning">Fixação de tela</a></li>
+ </ol>
+ </li>
+ <li><a href="#System">Sistema</a>
+ <ol>
+ <li><a href="#AppUsageStatistics">Estatísticas de uso do app</a></li>
+ </ol>
+ </li>
+ <li><a href="#Printing">Estrutura de impressão</a>
+ <ol>
+ <li><a href="#PDFRender">Processar PDF como bitmap</a></li>
+ </ol>
+ </li>
+ <li><a href="#TestingA11y">Testes e acessibilidade</a>
+ <ol>
+ <li><a href="#TestingA11yImprovements">Testes e aprimoramentos na acessibilidade</a></li>
+ </ol>
+ </li>
+ <li><a href="#IME">IME</a>
+ <ol>
+ <li><a href="#Switching">Fácil de alternar entre os idiomas de entrada</a></li>
+ </ol>
+ </li>
+ <li><a href="#Manifest">Declarações do manifesto</a>
+ <ol>
+ <li><a href="#ManifestFeatures">Recursos obrigatórios declaráveis</a></li>
+ <li><a href="#Permissions">Permissões de usuário</a></li>
+ </ol>
+ </li>
+</ol>
+
+<h2>Diferenças de API</h2>
+<ol>
+<li><a href="{@docRoot}sdk/api_diff/21/changes.html">Nível de API de 20 a 21 »</a> </li>
+<li><a href="{@docRoot}sdk/api_diff/preview-21/changes.html">Visualização do desenvolvedor de L a 21 »</a> </li>
+</ol>
+
+</div>
+</div>
+
+<p>Nível de API: {@sdkPlatformApiLevel}</p>
+
+<p>O Android 5.0 (<a href="{@docRoot}reference/android/os/Build.VERSION_CODES.html#LOLLIPOP">LOLLIPOP</a>) oferece novos recursos para usuários e desenvolvedores de apps. Este documento fornece uma introdução às novas APIs mais relevantes.</p>
+
+<p>Para uma visão de alto nível dos novos recursos da plataforma, veja os <a href="{@docRoot}about/versions/lollipop.html">destaques do Android Lollipop</a>.</p>
+
+
+<h3 id="Start">Começar a desenvolver</h3>
+
+<p>Para começar a criar apps para o Android 5.0, primeiro é preciso <a href="{@docRoot}sdk/index.html">conseguir o SDK do Android</a>. Depois disso, use o <a href="{@docRoot}tools/help/sdk-manager.html">Gerenciador de SDK</a> para fazer o download das imagens do sistema e da plataforma de SDK do Android 5.0.</p>
+
+<p style=" padding: 10px; background: #eee; width: 445px; border: 1px solid #ccc; margin-top: 20px;">Para testar seus apps em um dispositivo real, inclua um Nexus 5 ou 7 com a <br><a href="/preview/index.html#Start"><b>IMAGEM DE VISUALIZAÇÃO DO SISTEMA DO ANDROID</b></a>.</p>
+
+
+
+<h3 id="ApiLevel">Atualizar seu nível de API desejado</h3>
+
+<p>Para melhor otimizar seu app para os dispositivos executando Android {@sdkPlatformVersion}, defina <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> como <code>"{@sdkPlatformApiLevel}"</code>, instale o app em uma imagem do sistema do Android {@sdkPlatformVersion}, teste-a e, em seguida, publique o app atualizado com essa alteração.</p>
+
+<p>É possível usar as APIs do Android {@sdkPlatformVersion} ao mesmo tempo em que oferece suporte a versões mais antigas adicionando condições para o nível de API do sistema antes de executar APIs que não são compatíveis com seu <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a>. Para saber mais sobre a manutenção de compatibilidade com versões anteriores, leia <a href="{@docRoot}training/basics/supporting-devices/platforms.html">Suporte a diferentes versões de plataforma</a>.</p>
+
+<p>Para mais informações sobre como os níveis de API funcionam, leia <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">O que é um nível de API?</a></p>
+
+<h2 id="Behaviors">Alterações importantes de comportamento </h2>
+
+<p>Se você já tiver publicado um app para Android, esteja ciente de que seu app pode ser afetado por alterações feitas no Android 5.0.</p>
+
+<h3 id="ART">Se você ainda não tiver testado o app com o novo tempo de execução do Android (ART)…</h3>
+
+<p>A versão 4.4 apresentou um novo tempo de execução experimental do Android, o ART. Na versão 4.4, o ART era opcional, e o tempo de execução padrão continuava sendo o Dalvik. Com o Android 5.0, o ART agora é o tempo de execução padrão.</p>
+
+<p>Para uma visão geral dos novos recursos do ART, consulte <a href="https://source.android.com/devices/tech/dalvik/art.html">Introdução ao ART</a>. Alguns dos principais recursos novos são:</p>
+
+<ul>
+ <li>Compilação antecipada (AOT, na sigla em inglês)</li>
+ <li>Coleta de lixo aprimorada (GC, na sigla em inglês)</li>
+ <li>Suporte à depuração aprimorado</li>
+</ul>
+
+<p>A maioria dos apps para Android deve funcionar com o ART sem alterações. No entanto, algumas técnicas que funcionam em Dalvik não funcionam no ART. Para informações sobre os problemas mais importantes, consulte <a href="{@docRoot}guide/practices/verifying-apps-art.html">Verificação do comportamento do app no tempo de execução Android (ART)</a>. Preste especial atenção se:</p>
+
+<ul>
+ <li>O app usar interface nativa Java (JNI, na sigla em inglês) para executar código C/C++.</li>
+ <li>Você usar ferramentas de desenvolvedor que geram código não padrão (como alguns ofuscadores).</li>
+ <li>Você usar técnicas que são incompatíveis com a compactação de coleta de lixo. O ART não implementa a compactação de coleta de GC atualmente, mas essa compactação está em desenvolvimento no projeto de código aberto do Android.</li>
+</ul>
+
+<h3 id="BehaviorNotifications">Caso seu app implemente as notificações…</h3>
+
+<p>Verifique se suas notificações consideram essas alterações do Android 5.0. Para saber mais sobre como fazer as notificações para o Android 5.0 e superior, consulte o <a href="{@docRoot}design/patterns/notifications.html">Guia de design de notificações</a>.
+</p>
+
+<h4 id="NotificationsMaterialDesignStyle">Estilo do material design</h4>
+<p>As notificações são desenhadas com texto escuro em planos de fundo brancos (ou muito claros) para corresponder aos novos widgets de material design. Verifique a aparência de todas as suas notificações com o novo esquema de cores. Se o resultado não estiver bom, corrija-o:</p>
+
+<ul>
+ <li>Use {@link android.app.Notification.Builder#setColor(int) setColor()} para definir uma cor de destaque em um círculo atrás da imagem do ícone. </li>
+ <li>Atualize ou remova recursos que envolvam cor. O sistema ignora todos os canais não Alfa em ícones de ação e no ícone de notificação principal. Você deve partir do princípio de que esses ícones serão somente Alfa. O sistema desenha ícones de notificação em branco e ícones de ação em cinza escuro.</li>
+</ul>
+
+<h4 id="NotificationsSoundVibration">Som e vibração</h4>
+<p>Se atualmente você estiver adicionando sons e vibrações às suas notificações usando as classes {@link android.media.Ringtone}, {@link android.media.MediaPlayer} ou {@link android.os.Vibrator}, remova este código para que o sistema possa apresentar notificações de forma correta no modo de <em>prioridade</em>. Em vez disso, use métodos {@link android.app.Notification.Builder} para adicionar sons e vibração.</p>
+
+<p>Definir o dispositivo como {@link android.media.AudioManager#RINGER_MODE_SILENT RINGER_MODE_SILENT} faz com que o dispositivo entre no novo modo de prioridade. O dispositivo sai do modo prioridade se você o configurar para {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_NORMAL} ou {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_VIBRATE}.</p>
+
+<p>Anteriormente, o Android usava {@link android.media.AudioManager#STREAM_MUSIC STREAM_MUSIC} como o stream principal para controlar o volume em tablets. No Android 5.0, o stream de volume principal para dispositivos smartphone e tablet agora está unificado e é controlado por {@link android.media.AudioManager#STREAM_RING STREAM_RING} ou {@link android.media.AudioManager#STREAM_NOTIFICATION STREAM_NOTIFICATION}.</p>
+
+<h4 id="NotificationsLockscreenVisibility">Bloquear a visibilidade da tela</h4>
+<p>Por padrão, as notificações agora são exibidas na tela de bloqueio no Android 5.0. Os usuários podem optar por proteger informações confidenciais evitando que elas sejam expostas, caso em que o sistema automaticamente redige o texto exibido pela notificação. Para personalizar esta notificação redigida, use {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()}.</p>
+<p>Se a notificação não tiver informações pessoais ou se você desejar permitir o controle de reprodução de mídia na notificação, chame o método {@link android.app.Notification.Builder#setVisibility(int) setVisibility()} e defina o nível de visibilidade da notificação como {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}.
+</p>
+
+<h4 id="NotificationsMediaPlayback">Reprodução de mídia</h4>
+<p>Se você estiver implementando notificações que apresentam controles de transporte ou status de reprodução de mídia, considere a possibilidade de usar o novo modelo {@link android.app.Notification.MediaStyle}, em vez de um objeto {@link android.widget.RemoteViews.RemoteView} personalizado. Qualquer que seja a abordagem escolhida, defina a visibilidade da notificação como {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC} de modo que seus controles sejam acessíveis a partir da tela de bloqueio. Ao iniciar o Android 5.0, o sistema não mostra mais os objetos {@link android.media.RemoteControlClient} na tela de bloqueio. Para mais informações, consulte <a href="#BehaviorMediaControl">Caso seu app use RemoteControlClient</a>.</p>
+
+<h4 id="NotificationsHeadsup">Notificação de alerta</h4>
+<p>As notificações agora podem aparecer em uma pequena janela flutuante (também chamada de notificação de alerta) quando o dispositivo estiver ativo (isto é, o dispositivo estiver desbloqueado e sua tela ativada). Essas notificações aparecem de maneira semelhante à forma compacta da sua notificação, exceto que as de alerta também mostram botões de ação. Os usuários podem utilizar ou dispensar notificações de alerta sem sair do app atual.</p>
+
+<p>Exemplos de condições que podem acionar notificações de alerta incluem:</p>
+
+<ul>
+ <li>As atividades do usuário em modo de tela cheia (o app usa {@link android.app.Notification#fullScreenIntent})</li>
+ <li>A notificação tem prioridade alta e usa toques musicais ou vibrações</li>
+</ul>
+
+<p>Caso seu app implemente notificações em qualquer um desses cenários, verifique se as notificações de alerta são exibidas corretamente.</p>
+
+<h3 id="BehaviorMediaControl">Caso seu app use RemoteControlClient…</h3>
+<p>O uso da classe {@link android.media.RemoteControlClient} foi suspenso. Alterne para a nova {@link android.media.session.MediaSession} API assim que possível.</p>
+
+<p>O bloqueio de telas no Android 5.0 não mostra controles de transporte para {@link android.media.session.MediaSession} ou {@link android.media.RemoteControlClient}. Em vez disso, o app pode fornecer controle de reprodução de mídia de tela de bloqueio por meio de uma notificação. Isso dá ao app mais controle sobre a apresentação dos botões de mídia ao mesmo tempo em que fornece uma experiência consistente para usuários de dispositivos bloqueados e desbloqueados.</p>
+
+<p>O Android 5.0 apresenta um novo modelo {@link android.app.Notification.MediaStyle} para essa finalidade. {@link android.app.Notification.MediaStyle} converte as ações de notificação que você adicionou com {@link android.app.Notification.Builder#addAction(int, java.lang.CharSequence, android.app.PendingIntent) Notification.Builder.addAction()} em botões compactos incorporados às notificações de reprodução de mídia do seu app. Passar o token da sessão para o método {@link android.app.Notification.MediaStyle#setMediaSession(android.media.session.MediaSession.Token) setSession()} para informar o sistema de que essa notificação controla uma sessão de mídia em andamento.</p>
+
+<p>Defina a visibilidade da notificação como {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC} para marcar a notificação como segura a fim de ser exibida em qualquer tela de bloqueio (protegida ou não). Para mais informações, consulte <a href="#LockscreenNotifications">Notificações na tela de bloqueio</a>.</p>
+
+<p>Para exibir controles de reprodução de mídia se o app estiver em execução na plataforma da Android <a href="{@docRoot}tv/index.html">TV</a> ou do Android <a href="{@docRoot}wear/index.html">Wear</a>, implemente a classe {@link android.media.session.MediaSession}. Você também deve implementar {@link android.media.session.MediaSession} caso seu app precise receber eventos de botão de mídia em dispositivos Android.</p>
+
+<h3 id="BehaviorGetRecentTasks">Se o app usar getRecentTasks()…</h3>
+
+<p>Com a introdução dos novos recursos de <em>tarefas de atividades e documentos simultâneos</em> do Android 5.0 (consulte<a href="#Recents">Documentos simultâneos e atividades na tela de recentes</a> abaixo), o método {@link android.app.ActivityManager#getRecentTasks ActivityManager.getRecentTasks()} teve seu uso suspenso para aprimorar a privacidade do usuário. Para compatibilidade com versões anteriores, esse método ainda retorna um pequeno subconjunto de seus dados, incluindo a chamada de tarefas do próprio app e, possivelmente, outras tarefas não confidenciais (como Início). Se o app estiver usando esse método para recuperar suas próprias tarefas, use {@link android.app.ActivityManager#getAppTasks() getAppTasks()} em vez de recuperar essas informações.</p>
+
+<h3 id="64BitSupport">Caso você esteja usando o Kit de desenvolvimento nativo do Android (NDK, na sigla em inglês)…</h3>
+
+<p>O Android 5.0 apresenta o suporte a sistemas de 64 bits. O aprimoramento de 64 bits aumenta o espaço de endereço e melhora o desempenho ao mesmo tempo em que oferece suporte integral aos apps existentes de 32 bits. O suporte a 64 bits também melhora o desempenho de OpenSSL para criptografia. Além disso, a versão apresenta novas APIs do NDK de mídia nativas, bem como o suporte a OpenGL ES (GLES) 3.1.</p>
+
+<p>Para usar o suporte a 64 bits fornecidos no Android 5.0, faça o download e instale o NDK Revision 10c a partir da <a href="{@docRoot}tools/sdk/ndk/index.html">página NDK do Android</a>. Consulte as <a href="{@docRoot}tools/sdk/ndk/index.html#Revisions">notas da versão</a> do Revision 10c para mais informações sobre alterações importantes e correções de bug no NDK.</p>
+
+<h3 id="BindService">Caso seu app esteja associado a um serviço…</h3>
+
+<p>O método {@link android.content.Context#bindService(android.content.Intent, android.content.ServiceConnection, int) Context.bindService()} agora requer um {@link android.content.Intent} explícito e lança uma exceção se fornecido um propósito implícito. Para garantir que seu app é seguro, use um propósito explícito ao iniciar ou vincular seu {@link android.app.Service} e não declare filtros de intenção para o serviço.</p>
+
+<h3 id="BehaviorWebView">Caso seu app use WebView…</h3>
+
+<p>O Android 5.0 altera o comportamento padrão para o app.</p>
+<ul>
+<li><strong>Caso seu app segmente o nível 21 de API ou superior: </strong>
+ <ul>
+ <li>O sistema bloqueia o <a href="https://developer.mozilla.org/en-US/docs/Security/MixedContent" class="external-link">conteúdo misto</a> e cookies de terceiros por padrão. Para permitir conteúdo misto e cookies de terceiros, use os métodos {@link android.webkit.WebSettings#setMixedContentMode(int) setMixedContentMode()} e {@link android.webkit.CookieManager#setAcceptThirdPartyCookies(android.webkit.WebView, boolean) setAcceptThirdPartyCookies()} respectivamente.</li>
+ <li>O sistema agora escolhe de modo inteligente as partes do documento HTML que serão desenhadas. Esse novo comportamento padrão ajuda a reduzir a área ocupada na memória e aumenta o desempenho. Se você quiser processar o documento inteiro de uma só vez, desative essa otimização chamando {@link android.webkit.WebView#enableSlowWholeDocumentDraw()}.</li>
+ </ul>
+</li>
+<li><strong>Caso seu app segmente níveis de API inferiores a 21:</strong> o sistema permite conteúdo misto e cookies de terceiros, além de sempre processar o documento inteiro de uma vez.</li>
+</ul>
+
+<h2 id="UI">Interface do usuário</h2>
+
+<h3 id="MaterialDesign">Suporte ao material design</h3>
+
+<p>O lançamento futuro adiciona o suporte ao novo estilo do <em>material design</em> do Android. É possível criar apps com material design que é visualmente dinâmico e tem transições de elemento de interface do usuário que parecem naturais para os usuários. Esse suporte inclui:</p>
+
+<ul>
+
+ <li>O tema do material</li>
+ <li>Visualização de sombras</li>
+ <li>O widget {@link android.support.v7.widget.RecyclerView}</li>
+ <li>Animação drawable e efeitos de estilo</li>
+ <li>Animação de material design e efeitos de transição de atividade</li>
+ <li>Animadores para propriedades de visualização com base no estado da visualização</li>
+ <li>Elementos personalizáveis da interface do usuário e barras de app com paletas de cores controladas por você</li>
+ <li>Drawables animados e não animados com base nos gráficos de vetor XML</li>
+</ul>
+
+<p>Para saber mais sobre como adicionar a funcionalidade de material design ao seu app, consulte <a href="{@docRoot}training/material/index.html">Material design</a>.</p>
+
+<h3 id="Recents">Documentos simultâneos e atividades na tela de recentes</h3>
+
+<p>Em versões anteriores, a <a href="{@docRoot}guide/components/recents.html">tela de recentes</a> podia exibir somente uma tarefa para cada app com o qual o usuário tivesse interagido mais recentemente. Agora seu app pode abrir mais tarefas conforme necessário para outras atividades simultâneas para documentos. Esse recurso facilita fazer muitas tarefas ao mesmo tempo ao permitir que os usuários alternem rapidamente entre atividades individuais e documentos da tela de recentes, com uma experiência consistente de alternação entre todos os apps. Exemplos de tarefas simultâneas podem incluir guias abertas em um app para navegadores da Web, documentos em um app de produtividade, partidas simultâneas em um jogo ou bate-papos em um app de mensagens. O app pode gerenciar tarefas por meio da classe {@link android.app.ActivityManager.AppTask}.</p>
+
+<p>Para inserir uma interrupção lógica para que o sistema trate suas atividades como uma nova tarefa, use {@link android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT} ao iniciar a atividade com {@link android.app.Activity#startActivity(android.content.Intent) startActivity()}. Também é possível ter esse comportamento definindo o atributo do elemento <a href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a>{@code documentLaunchMode} como {@code "intoExisting"} ou {@code "always"} no seu manifesto.</p>
+
+<p>Para evitar que a tela de recentes fique bagunçada, defina o número máximo de tarefas do seu app que podem aparecer na tela. Para fazer isso, defina o atributo <a href="{@docRoot}guide/topics/manifest/application-element.html">&lt;application&gt;</a> {@link android.R.attr#maxRecents android:maxRecents}. O máximo que pode ser especificado atualmente é 50 tarefas por usuário (25 para dispositivos com pouca RAM).</a></p>
+
+<p>As tarefas na tela de recentes podem ser definidas para persistirem em reinicializações. Para controlar o comportamento de persistência, use o atributo <a href="{@docRoot}reference/android/R.attr.html#persistableMode">android:persistableMode</a>. Também é possível alterar as propriedades visuais de uma atividade na tela de recentes, como o rótulo, o ícone e a cor da atividade, chamando o método {@link android.app.Activity#setTaskDescription(android.app.ActivityManager.TaskDescription) setTaskDescription()}.</p>
+
+<h3 id="WebView">Atualizações de WebView</h3>
+<p>O Android 5.0 atualiza a implementação de {@link android.webkit.WebView} para o Chromium M37, com aprimoramentos de segurança e estabilidade, bem como correções de bugs. A string de user-agent padrão para um {@link android.webkit.WebView} executando no Android 5.0 foi atualizada para incorporar 37.0.0.0 como o número de versão.</p>
+
+<p>Essa versão apresenta a classe {@link android.webkit.PermissionRequest}, que permite ao seu app conceder a {@link android.webkit.WebView} permissão para acessar recursos protegidos, como a câmera e o microfone, por meio de APIs da Web, como <a href="https://developer.mozilla.org/en-US/docs/NavigatorUserMedia.getUserMedia" class="external-link">getUserMedia()</a>. Seu app precisa ter as permissões de Android apropriadas para esses recursos a fim de conceder as permissões para {@link android.webkit.WebView}.</p>
+
+<p>Com o novo método <code><a href="{@docRoot}reference/android/webkit/WebChromeClient.html#onShowFileChooser(android.webkit.WebView, android.webkit.ValueCallback<android.net.Uri[]>, android.webkit.WebChromeClient.FileChooserParams)">onShowFileChooser()</a></code>, é possível usar um campo de formulário de entrada em {@link android.webkit.WebView} e iniciar um seletor de arquivos para selecionar imagens e arquivos do dispositivo Android.</p>
+
+<p>Além disso, essa versão oferece suporte aos padrões abertos de <a href="http://webaudio.github.io/web-audio-api/" class="external-link">WebAudio</a>, <a href="https://www.khronos.org/webgl/" class="external-link">WebGL</a> e <a href="http://www.webrtc.org/" class="external-link">WebRTC</a>. Para saber mais sobre os novos recursos incluídos nessa versão, consulte <a href="https://developer.chrome.com/multidevice/webview/overview" class="external-link">WebView para Android</a>.</p>
+
+<h3 id="ScreenCapture">Compartilhamento e captura de tela</h3>
+<p>O Android 5.0 permite adicionar as funcionalidades de compartilhamento e captura de tela ao seu app com as novas APIs de {@link android.media.projection}. Essa funcionalidade é útil, por exemplo, se você desejar ativar o compartilhamento de tela em um app de conferência de vídeo.</p>
+
+<p>O novo método {@link android.media.projection.MediaProjection#createVirtualDisplay(java.lang.String, int, int, int, int, android.view.Surface, android.hardware.display.VirtualDisplay.Callback, android.os.Handler) createVirtualDisplay()} permite ao seu app capturar o conteúdo da tela principal (a exibição padrão) em um objeto {@link android.view.Surface}, que seu app pode enviar pela rede. A API permite capturar o conteúdo somente de telas não protegidas, e não captura áudio do sistema. Para começar a captura de tela, o app precisa solicitar a permissão do usuário iniciando uma caixa de diálogo de captura de tela usando um {@link android.content.Intent} obtido por meio do método {@link android.media.projection.MediaProjectionManager#createScreenCaptureIntent()}.</p>
+
+<p>Para ver um exemplo de como usar as novas APIs, consulte a classe {@code MediaProjectionDemo} no projeto de amostra.</p>
+
+<h2 id="Notifications">Notificações</h2>
+
+<h3 id="LockscreenNotifications">Notificações na tela bloqueada</h3>
+<p>As telas de bloqueio no Android 5.0 têm a capacidade de mostrar as notificações. Os usuários podem optar por meio das <em>Configurações</em> para permitir que conteúdo de notificação confidencial seja exibido em uma tela de bloqueio protegida.</p>
+
+<p>O app pode controlar o nível de detalhe visível quando as notificações são exibidas na tela de bloqueio segura. Para controlar o nível de visibilidade, chame {@link android.app.Notification.Builder#setVisibility(int) setVisibility()} e especifique um dos seguintes valores:</p>
+
+<ul>
+<li>{@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}: exibe informações básicas, como o ícone da notificação, mas oculta o conteúdo integral da notificação.</li>
+<li>{@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}: mostra o conteúdo integral da notificação.</li>
+<li>{@link android.app.Notification#VISIBILITY_SECRET VISIBILITY_SECRET}: mostra nada, exclui até o ícone de notificação.</li>
+</ul>
+
+<p>Quando o nível de visibilidade é {@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}, é possível fornecer uma versão redigida do conteúdo da notificação que oculta detalhes pessoais. Por exemplo, um app de mensagens SMS pode exibir uma notificação que mostra "Você tem três novas mensagens de texto", mas oculta o conteúdo da mensagem e os remetentes. Para fornecer essa notificação alternativa, crie primeiro a notificação de substituição usando {@link android.app.Notification.Builder}. Quando você criar o objeto de notificação privada, anexe a notificação de substituição a ele por meio do método {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()}.</p>
+
+<h3 id="NotificationsMetadata">Metadados de notificações</h3>
+<p>O Android 5.0 usa os metadados associados com as notificações do seu app para classificá-las de modo mais inteligente. Para definir os metadados, chame os métodos a seguir em {@link android.app.Notification.Builder} ao criar a notificação:</p>
+
+<ul>
+<li>{@link android.app.Notification.Builder#setCategory(java.lang.String) setCategory()}: informa ao sistema como lidar com as notificações do app quando o dispositivo estiver no modo de <em>prioridade</em>. Por exemplo, se uma notificação representar uma chamada de entrada, uma chamada instantânea ou um alarme.
+<li>{@link android.app.Notification.Builder#setPriority(int) setPriority()}: marca a notificação como mais ou menos importante do que as notificações normais. Notificações com o campo de prioridade definido como {@link android.app.Notification#PRIORITY_MAX PRIORITY_MAX} ou {@link android.app.Notification#PRIORITY_HIGH PRIORITY_HIGH} aparecem em uma pequena janela flutuante se a notificação também tem som ou vibração.</li>
+<li>{@link android.app.Notification.Builder#addPerson(java.lang.String) addPerson()}: permite adicionar uma ou mais pessoas que são relevantes para a notificação. O app pode usar isso para sinalizar para o sistema que ele deve agrupar notificações das pessoas especificadas ou classificar as notificações dessas pessoas como sendo mais importantes.</li>
+</ul>
+
+<h2 id="Graphics">Gráficos</h2>
+
+<h3 id="OpenGLES-3-1">Suporte para OpenGL ES 3.1 </h3>
+<p>O Android 5.0 adiciona o suporte nativo ao OpenGL ES 3.1 e interfaces Java. As novas e importantes funcionalidades fornecidas no OpenGL ES 3.1 incluem:</p>
+
+<ul>
+<li>Sombreadores de cálculo
+<li>Objetos sombreadores separados
+<li>Comandos draw indiretos
+<li>Texturas de estêncil e multiamostras
+<li>Aprimoramentos na linguagem de sombreamento
+<li>Extensões para os modos de mesclagem avançada e depuração
+<li>Compatibilidade de versões mais antigas com OpenGL ES 2.0 e 3.0
+</ul>
+
+<p>A interface Java para o OpenGL ES 3.1 no Android é fornecida com {@link android.opengl.GLES31}. Ao usar o OpenGL ES 3.1, declare isso em seu arquivo de manifesto junto com a tag <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> e o atributo {@code android:glEsVersion}. Por exemplo:</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:glEsVersion="0x00030001" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<p>Para mais informações sobre como usar o OpenGL ES, inclusive como verificar a versão do OpenGL ES compatível do dispositivo no tempo de execução, consulte o <a href="{@docRoot}guide/topics/graphics/opengl.html">Guia da OpenGL ES API</a>.</p>
+
+<h3 id="AndroidExtensionPack">Pacote de extensões para Android</h3>
+
+<p>Além do OpenGL ES 3.1, essa versão fornece um pacote de extensões com interfaces Java e suporte nativo para a funcionalidade de gráfico avançado. Essas extensões são tratadas como um único pacote pelo Android. Se a extensão {@code ANDROID_extension_pack_es31a} estiver presente, seu app poderá presumir que todas as extensões no pacote estão presentes e ativar os recursos de linguagem de sombreamento com uma única instrução {@code #extension}.</p>
+
+<p>O pacote de extensões oferece suporte a:</p>
+
+<ul>
+<li>Suporte garantido ao sombreador de fragmentos para buffers de armazenamento de sombreador, imagens e atomics (o suporte ao sombreador de fragmento é opcional no OpenGL ES 3.1.)</li>
+<li>Sombreadores de geometria e mosaico</li>
+<li>Formato de compactação de textura ASTC (LDR)</li>
+<li>Sombreamento e interpolação por amostra</li>
+<li>Modos diferentes de mesclagem para cada anexo colorido em um buffer de frame</li>
+</ul>
+
+<p>A interface Java para o pacote de extensões é fornecido com {@link android.opengl.GLES31Ext}. No manifesto do app, é possível declarar que o app precisa ser instalado somente em dispositivos que oferecem suporte ao pacote de extensões. Por exemplo:</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:name=“android.hardware.opengles.aep”
+ android:required="true" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<h2 id="Media">Mídia</h2>
+
+<h3 id="Camera-v2">Camera API para funcionalidades avançadas da câmera</h3>
+
+<p>O Android 5.0 apresenta a nova <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">android.hardware.camera2</a> API para facilitar o processamento de imagens e a captura de fotos com granulação baixa. Agora é possível acessar de maneira programática os dispositivos da câmera disponíveis para o sistema com {@link android.hardware.camera2.CameraManager#getCameraIdList() getCameraIdList()} e conectar um determinado dispositivo com {@link android.hardware.camera2.CameraManager#openCamera(java.lang.String, android.hardware.camera2.CameraDevice.StateCallback, android.os.Handler) openCamera()}. Para começar a capturar imagens, crie um {@link android.hardware.camera2.CameraCaptureSession} e especifique os objetos {@link android.view.Surface} para enviar imagens capturadas. O {@link android.hardware.camera2.CameraCaptureSession} pode ser configurado para tirar uma única foto ou várias imagens em uma sequência.</p>
+
+<p>Para ser notificado quando novas imagens são capturadas, implemente o listener {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} e defina-o na solicitação de captura. Agora quando o sistema conclui a solicitação de captura de imagem, seu listener {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} recebe uma chamada a {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback#onCaptureCompleted(android.hardware.camera2.CameraCaptureSession, android.hardware.camera2.CaptureRequest, android.hardware.camera2.TotalCaptureResult) onCaptureCompleted()}, fornecendo a você os metadados da captura de imagem em um {@link android.hardware.camera2.CaptureResult}.</p>
+
+<p>A classe {@link android.hardware.camera2.CameraCharacteristics} permite que seu app detecte quais recursos de câmera estão disponíveis em um dispositivo. A propriedade {@link android.hardware.camera2.CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL INFO_SUPPORTED_HARDWARE_LEVEL} do objeto representa o nível de funcionalidade da câmera.</p>
+
+<ul>
+ <li>Todos os dispositivos oferecem suporte pelo menos ao nível de hardware {@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY}, que tem recursos aproximadamente equivalentes aos da {@link android.hardware.Camera} API que teve seu uso suspenso.</li>
+ <li>Os dispositivos que oferecem suporte ao nível de hardware de {@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_FULL INFO_SUPPORTED_HARDWARE_LEVEL_FULL} são capazes de controlar manualmente a captura e o pós-processamento, além de capturar imagens em alta-resolução em altas taxas de frame.</li>
+</ul>
+
+<p>Para ver como usar a <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">Camera</a> API atualizada, consulte as amostras de implementação de {@code Camera2Basic} e {@code Camera2Video} nessa versão.</p>
+
+<h3 id="AudioPlayback">Reprodução de áudio</h3>
+<p>Essa versão inclui as seguintes alterações em {@link android.media.AudioTrack}:</p>
+<ul>
+ <li>Seu app agora pode fornecer dados de áudio no formato ponto flutuante ({@link android.media.AudioFormat#ENCODING_PCM_FLOAT ENCODING_PCM_FLOAT}). Isso permite uma maior escala dinâmica, uma precisão mais consistente e mais espaço. A aritmética de ponto flutuante é útil durante os cálculos intermediários. Os pontos de extremidade da reprodução usam o formato inteiro para dados de áudio e com profundidade de bits inferior. No Android 5.0, as partes do fluxo interno ainda não são ponto flutuante.
+ <li>Seu app agora pode fornecer dados de áudio como um {@link java.nio.ByteBuffer} no mesmo formato fornecido por {@link android.media.MediaCodec}.
+ <li>A opção {@link android.media.AudioTrack#WRITE_NON_BLOCKING WRITE_NON_BLOCKING} pode simplificar o armazenamento em buffer e multithreading de alguns apps.
+</ul>
+
+<h3 id="MediaPlaybackControl">Controle de reprodução de mídia</h3>
+<p>Use a nova notificação e APIs de mídia para garantir que a interface do usuário do sistema saiba da sua reprodução de mídia e possa extrair e mostrar a capa do álbum. Controlar a reprodução de mídia em uma interface do usuário agora é mais fácil com as novas classes {@link android.media.session.MediaSession} e {@link android.media.session.MediaController}.</p>
+
+<p>A nova classe {@link android.media.session.MediaSession} substitui a classe {@link android.media.RemoteControlClient} que teve seu uso suspenso e fornece um único conjunto de métodos de chamada de retorno para gerenciar os controles de transporte e os botões de mídia. Se o app fornecer a reprodução de mídia e for executado na plataforma Android <a href="{@docRoot}tv/index.html">TV</a> ou <a href="{@docRoot}wear/index.html">Android Wear</a>, use a classe {@link android.media.session.MediaSession} para lidar com os controles de transporte usando os mesmos métodos de chamada de retorno.</p>
+
+<p>É possível criar seu próprio app controlador de mídia com a nova classe {@link android.media.session.MediaController}. Essa classe oferece uma maneira de thread seguro para monitorar e controlar a reprodução de mídia do processo de interface do seu app. Ao criar um controlador, especifique um objeto {@link android.media.session.MediaSession.Token} para que seu app possa interagir com o {@link android.media.session.MediaSession} determinado. Usando os métodos {@link android.media.session.MediaController.TransportControls}, é possível enviar comandos como {@link android.media.session.MediaController.TransportControls#play() play()}, {@link android.media.session.MediaController.TransportControls#stop() stop()}, {@link android.media.session.MediaController.TransportControls#skipToNext() skipToNext()} e {@link android.media.session.MediaController.TransportControls#setRating(android.media.Rating) setRating()} para controlar a reprodução de mídia nessa sessão. Com o controlador, também é possível registrar um objeto {@link android.media.session.MediaController.Callback} para escutar os metadados e mudanças de estado da sessão.</p>
+
+<p>Além disso, é possível criar notificações ricas que permitem o controle de reprodução ligado a uma sessão de mídia com a nova classe {@link android.app.Notification.MediaStyle}.</p>
+
+<h3 id="MediaBrowsing">Navegação de mídia</h3>
+<p>O Android 5.0 apresenta a capacidade dos apps de procurar a biblioteca de conteúdo de mídia de outro app por meio da nova <a href="{@docRoot}reference/android/media/browse/package-summary.html">android.media.browse</a> API. Para expor o conteúdo de mídia no seu app, estenda a classe {@link android.service.media.MediaBrowserService}. Sua implementação de {@link android.service.media.MediaBrowserService} deve fornecer acesso a um {@link android.media.session.MediaSession.Token} para que apps possam reproduzir conteúdo de mídia fornecido por meio do seu serviço.</p>
+<p>Para interagir com o serviço de navegador de mídia, use a classe {@link android.media.browse.MediaBrowser}. Especifique o nome do componente para um {@link android.media.session.MediaSession} ao criar uma instância {@link android.media.browse.MediaBrowser}. Usando essa instância do navegador, seu app pode se conectar ao serviço associado e obter um objeto {@link android.media.session.MediaSession.Token} para reproduzir conteúdo exposto por meio do serviço.</p>
+
+<h2 id="Storage">Armazenamento</h2>
+
+<h3 id="DirectorySelection">Seleção do diretório</h3>
+
+<p>O Android 5.0 estende a <a href="{@docRoot}guide/topics/providers/document-provider.html">Estrutura de acesso ao armazenamento</a> para permitir que os usuários selecionem uma subárvore inteira de diretório, fornecendo aos apps o acesso de leitura/gravação a todos os documentos existentes sem exigir confirmação do usuário para cada item.</p>
+
+<p>Para selecionar uma subárvore de diretório, crie e envie um propósito {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE OPEN_DOCUMENT_TREE}. O sistema exibe todas as instâncias {@link android.provider.DocumentsProvider} que oferecem suporte à seleção de subárvore, permitindo que o usuário procure e selecione um diretório. O URI retornado representa o acesso à subárvore selecionada. É possível usar {@link android.provider.DocumentsContract#buildChildDocumentsUriUsingTree(android.net.Uri, java.lang.String) buildChildDocumentsUriUsingTree()} e {@link android.provider.DocumentsContract#buildDocumentUriUsingTree(android.net.Uri, java.lang.String) buildDocumentUriUsingTree()} juntamente com {@link android.content.ContentResolver#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String) query()} para explorar a subárvore.</p>
+
+<p>O novo método {@link android.provider.DocumentsContract#createDocument(android.content.ContentResolver, android.net.Uri, java.lang.String, java.lang.String) createDocument()} permite criar novos documentos ou diretórios em qualquer lugar abaixo da subárvore. Para gerenciar documentos existentes, use {@link android.provider.DocumentsContract#renameDocument(android.content.ContentResolver, android.net.Uri, java.lang.String) renameDocument()} e {@link android.provider.DocumentsProvider#deleteDocument(java.lang.String) deleteDocument()}. Confira o {@link android.provider.DocumentsContract.Document#COLUMN_FLAGS COLUMN_FLAGS} para verificar o suporte do provedor para essas chamadas antes de emiti-las.</p>
+
+<p>Se você estiver implementando um {@link android.provider.DocumentsProvider} e desejar oferecer suporte à seleção de subárvore, implemente {@link android.provider.DocumentsProvider#isChildDocument(java.lang.String, java.lang.String) isChildDocument()} e inclua {@link android.provider.DocumentsContract.Root#FLAG_SUPPORTS_IS_CHILD FLAG_SUPPORTS_IS_CHILD} em {@link android.provider.DocumentsContract.Root#COLUMN_FLAGS COLUMN_FLAGS}.</p>
+
+<p>O Android 5.0 também apresenta novos diretórios específicos ao pacote no armazenamento compartilhado no qual o app pode colocar arquivos de mídia para inclusão em {@link android.provider.MediaStore}. O novo {@link android.content.Context#getExternalMediaDirs()} retorna caminhos para esses diretórios em todos os dispositivos de armazenamento compartilhado. De forma semelhante a {@link android.content.Context#getExternalFilesDir(java.lang.String) getExternalFilesDir()}, permissões adicionais não são necessárias para que o app acesse os caminhos retornados. A plataforma periodicamente verifica novas mídias nesses diretórios, mas também é possível usar o {@link android.media.MediaScannerConnection} para verificar explicitamente se há novo conteúdo.</p>
+
+<h2 id="Wireless">Conectividade e sem fio</h2>
+
+<h3 id="Multinetwork">Várias conexões de rede</h3>
+<p>O Android 5.0 apresenta novas APIs de várias redes que permitem ao seu app verificar dinamicamente as redes disponíveis com recursos específicos, além de estabelecer uma conexão com eles. Essa funcionalidade é útil quando seu app exigir uma rede especializada, como SUPL, MMS ou uma rede de faturamento via operadora. Outro caso de uso é se você desejar enviar os dados usando um determinado tipo de protocolo de transporte.</p>
+
+<p>Para selecionar e se conectar a uma rede dinamicamente a partir do seu app, siga estas etapas:</p>
+
+<ol>
+ <li>Crie um {@link android.net.ConnectivityManager}.</li>
+ <li>Use a classe {@link android.net.NetworkRequest.Builder} para criar um objeto {@link android.net.NetworkRequest} e especificar os recursos de rede e o tipo de transporte nos quais seu app está interessado.</li>
+<li>Para buscar redes adequadas, chame {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} ou {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()} e passe o objeto {@link android.net.NetworkRequest} e uma implementação de {@link android.net.ConnectivityManager.NetworkCallback}. Use o método {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} se você quiser alternar para uma rede adequada após ela ser detectada. Para receber notificações somente de redes verificadas sem alternar ativamente, use o método {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()}.</li>
+</ol>
+
+<p>Quando o sistema detectar uma rede adequada, ele se conectará à rede e chamará a chamada de retorno {@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()}. É possível usar o objeto {@link android.net.Network} da chamada de retorno a fim de receber mais informações sobre a rede ou direcionar o tráfego para que a rede selecionada seja usada.</p>
+
+<h3 id="BluetoothBroadcasting">Bluetooth Low Energy</h3>
+<p>O Android 4.3 apresentou o suporte de plataforma para o <a href="{@docRoot}guide/topics/connectivity/bluetooth-le.html">Bluetooth Low Energy</a>(<em>Bluetooth LE</em>) na função central. No Android 5.0, um dispositivo Android agora pode agir como um <em>dispositivo periférico</em> de Bluetooth LE. Os apps podem usar esse recurso para fazer com que sua presença seja percebida pelos dispositivos vizinhos. É possível, por exemplo, criar apps que permitem que um dispositivo funcione como um pedômetro ou um monitor de integridade de dados e envie seus dados para outro dispositivo Bluetooth LE.</p>
+<p>As novas APIs de {@link android.bluetooth.le} permitem que seus apps divulguem anúncios, verifiquem respostas e formem conexões com dispositivos Bluetooth LE vizinhos. Para usar os novos recursos de publicidade e varredura, adicione a permissão {@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN} no manifesto. Quando os usuários atualizam ou fazem o download do seu app a partir da Play Store, eles são solicitados a conceder a seguinte permissão para seu app: "Informações da conexão Bluetooth: permite que o app controle o Bluetooth, incluindo a divulgação para dispositivos Bluetooth vizinhos ou a busca de informações sobre esses dispositivos."</p>
+
+<p>Para começar a publicidade de Bluetooth LE para que outros dispositivos possam descobrir seu app, chame {@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()} e passe uma implementação da classe {@link android.bluetooth.le.AdvertiseCallback}. O objeto de chamada de retorno recebe um relatório do sucesso ou da falha da operação de publicidade.</p>
+
+<p> O Android 5.0 apresenta a classe {@link android.bluetooth.le.ScanFilter} para que seu app possa buscar somente os tipos específicos de dispositivos nos quais está interessado. Para iniciar a busca de dispositivos Bluetooth LE, chame {@link android.bluetooth.le.BluetoothLeScanner#startScan(android.bluetooth.le.ScanCallback) startScan()} e passe uma lista de filtros. Na chamada de método, você precisa fornecer também uma implementação de {@link android.bluetooth.le.ScanCallback} para informar quando uma publicidade de Bluetooth LE for encontrada. </p>
+
+<h3 id="NFCEnhancements">Aprimoramentos na NFC</h3>
+<p>O Android 5.0 adiciona estas melhorias para permitir um uso mais amplo e flexível da NFC:</p>
+
+<ul>
+<li>O Android Beam agora está disponível no menu <em>Compartilhar</em>.</li>
+<li>Seu app pode chamar o Android Beam no dispositivo do usuário para compartilhar dados chamando {@link android.nfc.NfcAdapter#invokeBeam(android.app.Activity) invokeBeam()}. Isso evita a necessidade de o usuário manualmente tocar no dispositivo em relação a outro com capacidade para NFC a fim de concluir a transferência de dados.</li>
+<li>É possível usar o novo método {@link android.nfc.NdefRecord#createTextRecord(java.lang.String, java.lang.String) createTextRecord()} para criar um registro NDEF contendo dados de texto UTF-8.</li>
+<li>Se você estiver desenvolvendo um app de pagamentos, você agora tem a capacidade de registrar um código de app da NFC (AID, na sigla em inglês) dinamicamente chamando <code><a href="{@docRoot}reference/android/nfc/cardemulation/CardEmulation.html#registerAidsForService(android.content.ComponentName, java.lang.String, java.util.List<java.lang.String>)">registerAidsForService()</a></code>. Também é possível usar {@link android.nfc.cardemulation.CardEmulation#setPreferredService(android.app.Activity, android.content.ComponentName) setPreferredService()} para definir o serviço de emulação de cartão preferencial que deve ser usado quando uma atividade específica estiver em primeiro plano.</li>
+</ul>
+
+<h2 id="Power">Project Volta</h2>
+
+<p>Além de novos recursos, o Android 5.0 enfatiza melhorias na vida útil da bateria. Use as novas APIs e a ferramenta para compreender e otimizar o consumo de energia de seu app.</p>
+
+<h3 id="JobScheduler">Agendamento de tarefas</h3>
+<p>O Android 5.0 apresenta uma nova {@link android.app.job.JobScheduler} API que permite otimizar a vida útil da bateria definindo as tarefas para que o sistema execute de maneira assíncrona em um momento posterior ou sob condições especificadas (como quando o dispositivo está carregando). O agendamento de tarefa é útil em situações como:</p>
+<ul>
+ <li>O app não tem trabalho que não será visto pelo usuário, por isso é possível adiá-lo.</li>
+ <li>O app tem trabalho que você prefere fazer quando a unidade estiver ligada na tomada.</li>
+ <li>O app tem uma tarefa que requer acesso à rede ou uma conexão Wi-Fi.</li>
+ <li>O app tem uma série de tarefas que você deseja gerar como um lote em um agendamento regular.</li>
+
+</ul>
+
+<p>Uma unidade de trabalho está encapsulada por um objeto {@link android.app.job.JobInfo}. Esse objeto especifica os critérios de agendamento.</p>
+
+<p>Use a classe {@link android.app.job.JobInfo.Builder} para configurar como a tarefa agendada deve ser executada. É possível agendar a tarefa para ser executada em condições específicas, como:</p>
+
+<ul>
+ <li>Iniciar quando o dispositivo estiver carregando</li>
+ <li>Iniciar quando o dispositivo estiver conectado a uma rede não medida</li>
+ <li>Iniciar quando o dispositivo estiver ocioso</li>
+ <li>Terminar antes de um determinado prazo ou com o mínimo de atraso</li>
+</ul>
+
+<p>Por exemplo, é possível adicionar código como este para executar a tarefa em uma rede não medida:</p>
+
+<pre>
+JobInfo uploadTask = new JobInfo.Builder(mJobId,
+ mServiceComponent /* JobService component */)
+ .setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED)
+ .build();
+JobScheduler jobScheduler =
+ (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
+jobScheduler.schedule(uploadTask);
+</pre>
+
+<p>Se o dispositivo tiver energia estável (ou seja, se ele estiver conectado por mais de dois minutos e a bateria estiver em um <a href="{@docRoot}reference/android/content/Intent.html#ACTION_BATTERY_OKAY">nível de integridade</a>), o sistema executará a tarefa agendada que estiver pronta para execução, mesmo se o prazo dela não tiver expirado.</p>
+
+<p>Para ver um exemplo de como usar a {@link android.app.job.JobScheduler}API, consulte a amostra de implementação de {@code JobSchedulerSample} nesta versão.</p>
+
+<h3 id="PowerMeasurementTools">Ferramentas do desenvolvedor para uso da bateria</h3>
+
+<p>O novo comando {@code dumpsys batterystats} gera dados estatísticos interessantes sobre o uso da bateria em um dispositivo, organizados pelo código único do usuário (UID, na sigla em inglês). As estatísticas incluem:</p>
+
+<ul>
+<li>Histórico de eventos relacionados à bateria
+<li>Estatísticas globais para o dispositivo
+<li>Uso de energia aproximado por UID e o componente do sistema
+<li>Dispositivo móvel por app ms por pacote
+<li>Estatísticas agregadas de UID do sistema
+<li>Estatísticas agregadas de UID do app
+</ul>
+
+<p>Use a opção {@code --help} para saber mais sobre as diversas opções para adequar a saída. Por exemplo, para imprimir estatísticas de uso da bateria de um determinado pacote de apps desde que o dispositivo foi carregado pela última vez, execute este comando:
+<pre>
+$ adb shell dumpsys batterystats --charged &lt;package-name&gt;
+</pre>
+
+<p>É possível usar a ferramenta <a href="https://github.com/google/battery-historian" class="external-link">Battery Historian</a> na saída do comando {@code dumpsys} para gerar uma visualização de HTML de eventos relacionados à energia dos registros. Essa informação facilita para você entender e diagnosticar problemas relacionados à bateria.</p>
+
+<h2 id="Enterprise">Android no local de trabalho e na educação</h2>
+<h3 id="ManagedProvisioning">Provisionamento gerenciado</h3>
+
+<p>O Android 5.0 apresenta a nova funcionalidade para a execução de apps em um ambiente corporativo. Um <a href="{@docRoot}guide/topics/admin/device-admin.html">administrador de dispositivo</a> pode iniciar um processo de provisionamento gerenciado para adicionar um <em>perfil gerenciado</em> copresente, mas separado, a um dispositivo se o usuário tiver uma conta pessoal existente. Os apps que estão associados aos perfis gerenciados são exibidos junto a apps não gerenciados no inicializador do usuário, na tela de recentes e nas notificações.</p>
+
+<p>Para iniciar o processo de provisionamento gerenciado, envie {@link android.app.admin.DevicePolicyManager#ACTION_PROVISION_MANAGED_PROFILE ACTION_PROVISION_MANAGED_PROFILE} em um {@link android.content.Intent}. Se a chamada ocorrer, o sistema acionará a chamada de retorno {@link android.app.admin.DeviceAdminReceiver#onProfileProvisioningComplete(android.content.Context, android.content.Intent) onProfileProvisioningComplete()}. Será possível então chamar {@link android.app.admin.DevicePolicyManager#setProfileEnabled(android.content.ComponentName) setProfileEnabled()} para ativar esse perfil gerenciado.</p>
+
+<p>Por padrão, somente um pequeno subconjunto de apps são ativados no perfil gerenciado. É possível instalar mais apps no perfil gerenciado chamando {@link android.app.admin.DevicePolicyManager#enableSystemApp(android.content.ComponentName, android.content.Intent) enableSystemApp()}.</p>
+
+<p>Se você estiver desenvolvendo um app inicializador, será possível usar a nova classe {@link android.content.pm.LauncherApps} para ter uma lista das atividades inicializáveis do usuário atual e de quaisquer perfis gerenciados associados. O inicializador pode destacar visualmente os apps gerenciados acrescentando um selo de trabalho ao drawable do ícone. Para recuperar o ícone com selo, chame {@link android.content.pm.PackageManager#getUserBadgedIcon(android.graphics.drawable.Drawable, android.os.UserHandle) getUserBadgedIcon()}.</p>
+
+<p>Para saber como usar a nova funcionalidade, consulte a amostra de implementação de {@code BasicManagedProfile} nesta versão.</p>
+
+<h3 id="DeviceOwner">Proprietário do dispositivo</h3>
+<p>O Android 5.0 apresenta a capacidade de implantar um app do proprietário do dispositivo. O <em>proprietário do dispositivo</em> é um tipo especializado de <a href="{@docRoot}guide/topics/admin/device-admin.html">administrador de dispositivo</a> que tem a capacidade adicional de criar e remover usuários secundários, bem como definir configurações globais no dispositivo. Seu app de proprietário do dispositivo pode usar os métodos na classe {@link android.app.admin.DevicePolicyManager} para tirar o controle de granulação da configuração, da segurança e dos apps em dispositivos gerenciados. Um dispositivo pode ter somente um proprietário ativo de cada vez.</p>
+
+<p>Para implantar e ativar um proprietário do dispositivo, você precisa realizar uma transferência de dados de NFC de um app de programação para o dispositivo enquanto o dispositivo estiver em seu estado não provisionado. Essa transferência de dados envia as mesmas informações presentes no propósito de provisionamento descrito no <a href="#ManagedProvisioning">Provisionamento gerenciado</a>.</p>
+
+<h3 id="ScreenPinning">Fixação de tela</h3>
+
+<p>O Android 5.0 apresenta uma nova API de fixação de tela que permite restringir temporariamente a saída dos usuários de sua tarefa ou que eles sejam interrompidos por notificações. Isso pode ser usado, por exemplo, se você desenvolve um app educacional compatível com requisitos de avaliação de alto risco no Android ou em um app de quiosque com um único objetivo. Depois que o app ativar a fixação de tela, os usuários não podem ver as notificações, acessar outros apps ou retornar para a tela inicial do app até saírem do modo.</p>
+
+<p>Existem duas maneiras de ativar a fixação de tela:</p>
+
+<ul>
+<li><strong>Manualmente:</strong> os usuários podem ativar a fixação de tela em <em>Configurações &gt; Segurança &gt; Fixação de tela </em> e selecionar as tarefas que desejam fixar tocando no ícone de fixação verde na tela de recentes.</li> <li><strong>De maneira programática: </strong>para ativar a fixação de tela de maneira programática, chame {@link android.app.Activity#startLockTask() startLockTask()} a partir do seu app. Se o app solicitante não for um proprietário do dispositivo, o usuário será solicitado a confirmar. Um app de proprietário do dispositivo pode chamar o método {@link android.app.admin.DevicePolicyManager#setLockTaskPackages(android.content.ComponentName, java.lang.String[]) setLockTaskPackages()} para ativar a opção para que os apps possam ser fixados sem a etapa de confirmação do usuário.</li>
+</ul>
+
+<p>Quando o bloqueio de tarefa estiver ativo, o seguinte comportamento ocorre:</p>
+
+<ul>
+<li>A barra de status está em branco e as notificações do usuário e as informações de status estão ocultas.</li>
+<li>Os botões "Início" e "Recentes" estão ocultos.</li>
+<li>Outros apps não podem lançar novas atividades.</li>
+<li>O app atual pode iniciar novas atividades, contanto que não crie novas tarefas.</li>
+<li>Quando o recurso de fixação de tela é chamado por um proprietário do dispositivo, o usuário permanece bloqueado para seu app, até que o app chame {@link android.app.Activity#stopLockTask() stopLockTask()}.</li>
+<li>Se a fixação de tela é a atividade executada por outro app que não é proprietário do dispositivo ou pelo usuário diretamente, o usuário pode sair mantendo pressionados os botões Voltar e Recentes.</li>
+
+</ul>
+
+<h2 id="Printing">Impressão de framework</h2>
+
+<h3 id="PDFRender">Renderizar PDF como bitmap</h3>
+<p>Agora é possível processar páginas de documentos PDF para imagens de bitmap e imprimi-las usando a nova classe {@link android.graphics.pdf.PdfRenderer}. Você deve especificar um {@link android.os.ParcelFileDescriptor} que seja buscável (isto é, o conteúdo poderá ser acessado aleatoriamente) e no qual o sistema registre o conteúdo imprimível. O app pode obter uma página para processar com {@link android.graphics.pdf.PdfRenderer#openPage(int) openPage()} e depois chamar {@link android.graphics.pdf.PdfRenderer.Page#render(android.graphics.Bitmap, android.graphics.Rect, android.graphics.Matrix, int) render()} para desativar o {@link android.graphics.pdf.PdfRenderer.Page} aberto em um bitmap. Também é possível definir parâmetros adicionais se você somente deseja converter uma parte do documento em uma imagem de bitmap (por exemplo, para implementar uma <a href="http://en.wikipedia.org/wiki/Tiled_rendering" class="external-link">renderização de bloco</a> para zoom no documento).</p>
+
+<p>Para obter um exemplo de como usar as novas APIs, consulte o exemplo {@code PdfRendererBasic}.</p>
+
+<h2 id="System">Sistema</h2>
+<h3 id="AppUsageStatistics">Estatísticas de uso do app</h3>
+<p>Agora é possível acessar o histórico de utilização em um dispositivo Android com a nova {@link android.app.usage} API. Essa API fornece informações mais detalhadas sobre o uso do método suspenso {@link android.app.ActivityManager#getRecentTasks(int, int) getRecentTasks()}. Para usar essa API, primeiro é preciso declarar a permissão {@code "android.permission.PACKAGE_USAGE_STATS"} em seu manifesto. O usuário também deve permitir o acesso do app por meio de <em>Configurações &gt; Segurança &gt; Apps</em> com acesso de uso.</p>
+
+<p>O sistema coleta os dados de uso por apps, agregando os dados em intervalos diários, semanais, mensais e anuais. A duração máxima pela qual o sistema mantém esses dados é:</p>
+
+<ul>
+ <li>Dados diários: sete dias</li>
+ <li>Dados semanais: quatro semanas</li>
+ <li>Dados mensais: seis meses</li>
+ <li>Dados anuais: dois anos</li>
+</ul>
+
+<p>Para cada app, o sistema registra os seguintes dados:</p>
+<ul>
+<li>A última vez em que o app foi usado</li>
+<li>O tempo total em que o app esteve em primeiro plano pelo intervalo de tempo (por dia, semana, mês ou ano)</li>
+<li>Captura de carimbo de hora de um componente (identificado por um pacote e pelo nome da atividade) movido ao primeiro plano ou ao plano de fundo durante um dia</li>
+<li>Captura de carimbo de hora quando a configuração de um dispositivo foi alterada (por exemplo, quando a orientação do dispositivo foi alterada devido à rotação)</li>
+</ul>
+
+<h2 id="TestingA11y">Testes e acessibilidade </h2>
+
+<h3 id="TestingA11yImprovements">Melhorias de testes e acessibilidade</h3>
+<p>O Android 5.0 adiciona o seguinte suporte a testes e acessibilidade:</p>
+
+<ul>
+<li>Os novos métodos {@link android.app.UiAutomation#getWindowAnimationFrameStats() getWindowAnimationFrameStats()} e {@link android.app.UiAutomation#getWindowContentFrameStats(int) getWindowContentFrameStats()} capturam estatísticas de frame para animações de janelas e conteúdos. Esses métodos permitem registrar testes de instrumentação para avaliar se o app processa quadros em uma frequência de atualização suficiente para fornecer uma experiência contínua ao usuário.</li>
+
+<li>O novo método {@link android.app.UiAutomation#executeShellCommand(java.lang.String) executeShellCommand()} permite executar comandos do shell no teste de instrumentação. A execução do comando é semelhante à execução de {@code adb shell} em um host conectado ao dispositivo, permitindo o uso de ferramentas de shell como {@code dumpsys}, {@code am}, {@code content} e {@code pm}.</li>
+
+<li>Serviços de acessibilidade e ferramentas de teste que usam APIs de acessibilidade (como <a href="{@docRoot}tools/help/uiautomator/index.html">{@code UiAutomator}</a>) podem agora recuperar informações detalhadas sobre as propriedades das janelas na tela com as quais os usuários com problemas visuais podem interagir. Para recuperar uma lista de objetos {@link android.view.accessibility.AccessibilityWindowInfo}, chame o novo método {@link android.accessibilityservice.AccessibilityService#getWindows() getWindows()}.</li>
+
+<li>A nova classe {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} permite definir ações padrão ou personalizadas para executar em um {@link android.view.accessibility.AccessibilityNodeInfo}. A nova classe {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} substitui as APIs relativas a ações anteriormente encontradas em {@link android.view.accessibility.AccessibilityNodeInfo}.</li>
+
+<li>O Android 5.0 fornece um controle mais detalhado sobre síntese de conversão de texto em voz. A nova classe {@link android.speech.tts.Voice} permite que o app use perfis de voz associados a locais específicos, classificação de qualidade e latência e parâmetros específicos de mecanismos de conversão de texto em voz.</li>
+</ul>
+
+<h2 id="IME">IME</h2>
+
+<h3 id="Switching">Troca facilitada entre idiomas de entrada</h3>
+
+<p>A partir do Android 5.0, os usuários podem facilmente alternar entre todos os <a href="{@docRoot}guide/topics/text/creating-input-method.html">editores de método de entrada (IME)</a> compatíveis com a plataforma. Executar a ação de comutação designada (normalmente tocando o ícone de globo no teclado virtual) percorre todos os IMEs. Essa mudança de comportamento foi implementada pelo método {@link android.view.inputmethod.InputMethodManager#shouldOfferSwitchingToNextInputMethod(android.os.IBinder) shouldOfferSwitchingToNextInputMethod()}.</p>
+
+<p>Além disso, o framework agora verifica se o próximo IME inclui um mecanismo de alternação (e, portanto, se o IME é compatível com a alternação posterior ao IME). Um IME com mecanismo de alternação não passará a outro IME sem esse mecanismo. Essa mudança de comportamento foi implementada pelo método {@link android.view.inputmethod.InputMethodManager#switchToNextInputMethod(android.os.IBinder, boolean) switchToNextInputMethod()}.
+
+<p>Para saber um exemplo de como usar as APIs de alternação de IME atualizadas, consulte o exemplo atualizado de implementação de teclado virtual nesta versão. Para saber mais sobre como implementar a troca entre IMEs, consulte <a href="{@docRoot}guide/topics/text/creating-input-method.html">Criação de um método de entrada</a>.
+</p>
+
+<h2 id="Manifest">Declarações de manifesto</h2>
+
+<h3 id="ManifestFeatures">Recursos necessários declaráveis</h3>
+<p>Os seguintes valores agora são compatíveis no elemento <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a>, para garantir que o app seja instalado somente em dispositivos que fornecem os recursos necessários.</p>
+
+<ul>
+<li>{@link android.content.pm.PackageManager#FEATURE_AUDIO_OUTPUT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_POST_PROCESSING}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_SENSOR}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_RAW}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_LEVEL_FULL}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_GAMEPAD}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LIVE_TV}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_MANAGED_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LEANBACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_OPENGLES_EXTENSION_PACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SECURELY_REMOVES_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_AMBIENT_TEMPERATURE}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_HEART_RATE_ECG}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_RELATIVE_HUMIDITY}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_VERIFIED_BOOT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_WEBVIEW}</li>
+</ul>
+
+<h3 id="Permissions">Permissões do usuário</h3>
+
+<p>A seguinte permissão agora é compatível com o elemento <a href="{@docRoot}guide/topics/manifest/uses-permission-element.html">{@code <uses-permission>}</a> para declarar as permissões exigidas por seu app para o acesso a algumas APIs.</p>
+
+<ul>
+<li>{@link android.Manifest.permission#BIND_DREAM_SERVICE}: ao segmentar para a API nível 21 ou superior, essa permissão é necessária por um serviço do <a href="{@docRoot}about/versions/android-4.2.html#Daydream">Daydream</a>, para garantir que somente o sistema pode se vincular a ele.</li>
+</ul>
diff --git a/docs/html-intl/intl/pt-br/about/versions/lollipop.jd b/docs/html-intl/intl/pt-br/about/versions/lollipop.jd
new file mode 100644
index 0000000..cb76376
--- /dev/null
+++ b/docs/html-intl/intl/pt-br/about/versions/lollipop.jd
@@ -0,0 +1,256 @@
+page.title=Android Lollipop
+
+@jd:body
+
+
+
+
+
+
+
+ <div style="padding:0px 0px 0px 20px;float:right;margin:0 -10px 0 0">
+ <img src="{@docRoot}images/home/l-hero_2x.png" srcset="{@docRoot}images/home/l-hero.png 1x, {@docRoot}images/home/l-hero_2x.png 2x" width="460" height="300" >
+ </div>
+
+ <div class="landing-docs" style="float:right;clear:both;margin:68px 0 2em 3em;">
+ <div class="col-4 normal-links highlights" style="font-size:12px;">
+ <h3 id="thisd" >Principais recursos para desenvolvedores</h3>
+ <ul style="list-style-type:none;">
+ <li><a href="#Material">Material design</a></li>
+ <li><a href="#Perf">Foco no desempenho</a></li>
+ <li><a href="#Notifications">Notificações</a></li>
+ <li><a href="#TV">Seu apps na tela grande</a></li>
+ <li><a href="#Documents">Apps centrados em documentos</a></li>
+ <li><a href="#Connectivity">Conectividade avançada</a></li>
+ <li><a href="#Graphics">Gráficos de alto desempenho</a></li>
+ <li><a href="#Audio">Áudio mais potente</a></li>
+ <li><a href="#Camera">Câmera e vídeo aprimorados</a></li>
+ <li><a href="#Work">Android no local de trabalho</a></li>
+ <li><a href="#ScreenCapture">Compartilhamento e captura de tela</a></li>
+ <li><a href="#Sensors">Novos tipos de sensores</a></li>
+ <li><a href="#WebView">Chromium WebView</a></li>
+ <li><a href="#Accessibility">Acessibilidade e entrada </a></li>
+ <li><a href="#Battery">Ferramentas para apps com consumo eficaz de bateria</a></li>
+ </ul>
+ </div>
+</div>
+
+
+
+
+
+
+
+<p>Bem-vindo ao Android 5.0 Lollipop, a maior e mais ambiciosa versão para Android já lançada!</p>
+
+<p>Esta versão está repleta de novos recursos para usuários e milhares de novas APIs para desenvolvedores. Ele expande o Android ainda mais, de telefones, tablets e acessórios a TVs e carros.</p>
+
+<p>Para uma análise mais detalhada das novas APIs para desenvolvedores, consulte a <a href="{@docRoot}about/versions/android-5.0.html">Visão geral da API do Android 5.0</a>. Ou leia mais sobre o Android 5.0 para consumidores em <a href="http://www.android.com/versions/lollipop-5-0/">www.android.com</a>.</p>
+
+
+
+<p style=" padding: 10px; background: #eee; width: 250px; border: 1px solid #ccc; margin-top: 20px;">Para testar seus apps em um dispositivo real, inclua um Nexus 5 ou 7 com a <br><a href="/preview/index.html#Start"><b>IMAGEM DE VISUALIZAÇÃO DO SISTEMA DO ANDROID</b></a>.</p>
+
+
+<h2 id="Material">Material design</h2>
+
+<p>O Android 5.0 traz o <a href="http://www.google.com/design/spec">Material design</a> para o Android e fornece um kit de ferramentas de interface de usuário para integrar os novos padrões de design facilmente em seus apps. </p>
+
+
+
+<p>Novas <strong>visualizações em 3D</strong>permitem que você defina um nível z para aumentar os elementos de fora da hierarquia de visualização e projetar <strong>sombras em tempo real</strong>, mesmo ao se moverem.</p>
+
+
+<p><strong>Transições de atividades</strong> incorporadas levam o usuário diretamente de um estado para outro, com movimentos bonitos e animados. O tema do material adiciona transições para suas atividades, incluindo a capacidade de usar <strong>elementos visuais compartilhados</strong> em atividades.</p>
+
+
+
+<div style="width:290px;margin-right:35px;float:left">
+ <div class="framed-nexus5-port-span-5">
+ <video class="play-on-hover" autoplay="">
+ <source src="/design/material/videos/ContactsAnim.mp4">
+ <source src="/design/videos/ContactsAnim.webm">
+ <source src="/design/videos/ContactsAnim.ogv">
+ </video>
+ </div>
+ <div style="font-size:10pt;margin-left:20px;margin-bottom:30px">
+ <em>Para reproduzir o filme, clique na tela do dispositivo</em>
+ </div>
+</div>
+
+
+<p>Animações com ondulação estão disponíveis para botões, caixas de seleção e outros controles de toque em seu app.
+
+<p>Você também pode definir drawables de vetor em XML e animá-los de várias formas. Drawables de vetor são dimensionados sem perder definição, então eles são perfeitos para ícones de uma cor em apps.</p>
+
+<p>Um novo agrupamento de processamento gerenciado pelo sistema, chamado de <strong>RenderThread</strong>, mantém as animações suaves, mesmo quando há atrasos no agrupamento da interface de usuário principal. </p>
+
+
+<h2 id="Perf">Foco no desempenho</h2>
+
+<p>O Android 5.0 fornece uma experiência de computação mais rápida, mais suave e mais poderosa.</p>
+
+<p>O Android agora é executado exclusivamente no novo <strong>tempo de execução ART</strong>, criado desde o início para oferecer suporte a uma mistura entre código AOT, JIT e interpretado. Ele é compatível com arquiteturas ARM, x86 e MIPS e é totalmente compatível com 64 bits.</p>
+
+<p>ART melhora o desempenho e a resposta do app. A coleta eficiente de lixo reduz o número e a duração de pausas para eventos GC, o que se ajusta confortavelmente na janela de sincronização vertical para que seu app não ignore quadros. ART também move dinamicamente a memória para otimizar o desempenho para os usos de primeiro plano. </p>
+
+<p>O Android 5.0 introduz suporte de plataforma para <strong>arquiteturas de 64 bits</strong>, usadas pelo NVIDIA Tegra K1 do Nexus 9. Otimizações fornecem maior espaço de endereço e desempenho aprimorado para certas cargas de trabalho de cálculo. Apps escritos na linguagem Java são executados como apps de 64 bits automaticamente sem a necessidade de modificações. Se o app usar código nativo, estendemos o NDK para oferecer suporte a novos ABIs para ARM v8, x86-64 e MIPS-64.</p>
+
+<p>Com o contínuo foco no desempenho mais suave, o Android 5.0 oferece maior sincronização audiovisual. O fluxo de áudio e de gráficos foi instrumentalizado para marcações de tempo mais precisas, possibilitando que apps de vídeo e jogos exibam conteúdos sincronizados de forma suave.</p>
+
+
+<h2 id="Notifications">Notificações</h2>
+
+<p>As notificações no Android 5.0 estão mais visíveis, acessíveis e configuráveis. </p>
+
+<img src="{@docRoot}images/versions/notification-headsup.png" style="float:right; margin:0 0 40px 60px" width="300" height="224" />
+
+<p>Se o usuário quiser, diferentes detalhes de notificações podem aparecer <strong>na tela de bloqueio</strong>. Os usuários podem optar pela exibição de nenhuma notificação de conteúdo, algumas notificações ou notificações de todo o conteúdo na tela de bloqueio de segurança. </p>
+
+<p>Os principais alertas de notificação, como as chamadas recebidas, aparecem nas <strong>notificações de alerta</strong>, uma pequena janela flutuante que permite que o usuário responda ou descarte sem sair do app atual.</p>
+
+<p>Agora você pode adicionar <strong>novos metadados</strong> a notificações para coletar contatos associados (para classificação), categoria e prioridade.</p>
+
+<p>Um novo modelo de notificação para mídia fornece controles de mídia consistentes para notificações com até 6 botões de ação, incluindo controles personalizados como "polegar para cima", sem a necessidade de RemoteViews!</p>
+
+
+
+<h2 id="TV">Seus apps na tela grande</h2>
+
+<p>A <a href="http://developer.android.com/tv/index.html">Android TV</a>oferece uma plataforma completa de TV para a experiência de tela grande no app. A Android TV está centrada na experiência da tela inicial simplificada, que permite que os usuários descubram conteúdos facilmente, com recomendações personalizadas e pesquisa por voz.</p>
+
+<p>Com a Android TV, você agora pode <strong>criar experiências grandes e arrojadas</strong> para o conteúdo do seu app ou jogo e oferecer suporte a interações com controles de jogo e outros dispositivos de entrada. Para ajudar a criar interfaces de usuário cinematográficas, com 3 metros, para televisão, o Android fornece uma <strong>estrutura de interface de usuário</strong> na <a href="{@docRoot}tools/support-library/features.html#v17-leanback">biblioteca de suporte v17</a>.</p>
+
+<p>A <strong>Estrutura de Entrada da Android TV</strong>(TIF) permite que apps suportem transmissões de vídeo de fontes como entradas HDMI, sintonizadores de TV e receptores IPTV. Ele também ativa a pesquisa de TV ao vivo por meio de metadados publicados pela entrada da TV e inclui um Serviço de controle HDMI-CEC para suportar diversos dispositivos com um único controle remoto. </p>
+
+<p>A Estrutura de Entrada de TV fornece acesso a uma variedade de fontes de entrada de TV ao vivo e as reúne em uma única interface para que usuários naveguem, visualizem e desfrutem do conteúdo. A criação de um serviço de entrada de TV para seu conteúdo pode ajudar a tornar o conteúdo mais acessível em dispositivos de TV.</p>
+
+
+
+<img src="{@docRoot}images/versions/recents_screen_2x.png" srcset="{@docRoot}images/versions/recents_screen.png 1x, {@docRoot}images/versions/recents_screen_2x.png 2x" style="float:right; margin:0 0 40px 60px" width="300" height="521" />
+
+<h2 id="Documents">Apps centrados em documentos</h2>
+
+<p>O Android 5.0 apresenta um espaço de Visão geral redesenhado (anteriormente chamado de Recentes), que está mais versátil e útil para a realização de múltiplas tarefas.</p>
+
+<p>Novas APIs permitem exibir atividades separadas em seu app, como documentos individuais juntamente com outras telas recentes.</p>
+
+<p>Você pode aproveitar os documentos simultâneos para fornecer aos usuários acesso instantâneo a mais dos seus conteúdos ou serviços. Por exemplo, você pode usar documentos simultâneos para representar arquivos em um app de player de produtividade, correspondências em um jogo ou de bate-papo em um app de mensagens. </p>
+
+
+
+<h2 id="Connectivity">Conectividade avançada</h2>
+
+<p>O Android 5.0 adiciona novas APIs que permitem que os apps realizem operações simultâneas com o <strong>Bluetooth Low Energy</strong> (BLE), permitindo a varredura (modo central) e a publicidade (modo periférico).</p>
+
+<p>Novos recursos de <strong>múltiplas redes</strong> permitem que os apps consultem redes disponíveis para os recursos disponíveis, como Wi-Fi, celular, medido, ou fornecer determinados recursos de rede. Em seguida, o app pode solicitar uma conexão e responder à perda de conectividade ou a outras alterações de rede.</p>
+
+<p>As APIs da <strong>NFC</strong> agora permitem que os apps registrem um código de app da NFC (AID, na sigla em inglês) dinamicamente. Elas também podem definir o serviço de emulação de cartão preferencial por serviço ativo e criar um registro de NDEF contendo dados de texto UTF 8.</p>
+
+
+
+<h2 id="Graphics">Gráficos de alto desempenho</h2>
+
+<p>O suporte para o <strong><a href="http://www.khronos.org/opengles/3_X/">Khronos OpenGL ES 3.1</a></strong> agora oferece capacidade gráfica 2D e 3D de alto desempenho para jogos e outros apps nos dispositivos compatíveis. </p>
+
+<p>O OpenGL ES 3.1 adiciona sombreadores de cálculo Shaders, texturas de estêncil, efeitos visuais acelerados, compressão de textura ETC2/EAC de alta qualidade, renderização avançada de texturas, tamanho padronizado de texturas, formatos de processamento de buffer etc.</p>
+
+
+<div class="figure" style="width:350px; margin:0 0 0 60px">
+<img src="{@docRoot}images/versions/rivalknights.png" style="float:right;" width="350" height="525" />
+<p class="img-caption">Rival Knights, da Gameloft, usa compressão de texturas escalonáveis adaptáveis (ASTC) de AEP e sombreadores de cálculo do ES 3.1 para apresentar efeitos de florescimento em HDR e oferecer maior detalhamento gráfico.</p>
+</div>
+
+<p>O Android 5.0 também apresenta o <strong>Pacote de Extensões do Android</strong> (AEP), um conjunto de extensões do OpenGL ES que fornece acesso a recursos, como sombreadores de mosaico, sombreadores de geometria, compressão de texturas ASTC, interpolação por amostra e sombreamento e outros recursos avançados de renderização. Com o AEP, você pode fornecer gráficos de alto desempenho em diversas GPUs.</p>
+
+
+<h2 id="Audio">Áudio mais potente</h2>
+
+<p>Um novo design de captura de áudio oferece uma <strong>entrada de áudio de baixa latência</strong>. O novo design inclui: uma faixa de captura rápida que nunca bloqueia, exceto durante uma leitura; clientes de captura rápida de faixas em faixas de amostras nativas, contagem de canais e profundidade de bits; e os clientes de captura normal oferecem nova amostra, mixagem de canais cima/baixo e profundidade de bits cima/baixo.</p>
+
+<p><strong>A mixagem de streaming de áudio</strong> de vários canais permite que apps profissionais de áudio mixem até oito canais, incluindo canais 5.1 e 7.1.</p>
+
+<p>Apps podem expor seu conteúdo de mídia, <strong>procurar mídia</strong> de outros apps e solicitar reprodução. O conteúdo é exposto por meio de uma interface de consulta e não precisa residir no dispositivo.</p>
+
+<p>Apps têm um melhor controle de granulação sobre a <strong>síntese texto-fala</strong> por meio de perfis de voz que estão associados a locais, qualidade e classificação de latência específicos. Novas APIs também aprimoram o suporte para verificar erros de síntese, sínteses de rede, descobertas de idioma e substituições de rede.</p>
+
+<p>O Android agora inclui suporte ao padrão de periféricos de <strong>áudio USB</strong>, permitindo que os usuários conectem fones de ouvido, alto-falantes, microfones USB ou outros periféricos digitais de alto desempenho. O Android 5.0 também adiciona suporte a codecs de áudio <strong>Opus</strong>.</p>
+
+<p>Novas APIs de <strong>{@link android.media.session.MediaSession}</strong> para controle da reprodução de mídia agora facilitam o fornecimento de controles de mídia entre telas e outros controladores.</p>
+
+
+<h2 id="Camera">Câmera e vídeo aprimorados</h2>
+
+<p>O Android 5.0 apresenta <strong>todas as novas APIs de câmeras</strong> que permitem capturar formatos brutos como YUV e Bayer RAW, bem como parâmetros de controle como tempo de exposição, sensibilidade ISO e duração de frame com base por frame. O novo fluxo de câmera totalmente sincronizado permite capturar imagens YUV sem compressão e com a mais alta resolução em 30 QPS em dispositivos compatíveis.</p>
+
+<p>Além de imagens, também é possível capturar metadados, como modelos de ruído, e informações ópticas da câmera.</p>
+
+<p>Apps que enviam streamings pela rede agora podem aproveitar a <strong>codificação de vídeo de alta eficiência (HEVC, na sigla em inglês)</strong> do H.265 para aumentar a codificação e a decodificação dos dados em vídeo. </p>
+
+<p>O Android 5.0 também adiciona suporte a <strong>encapsulamento de multimídia</strong> para proporcionar a melhor experiência possível ao conteúdo de definição ultra-alta (4K) e a capacidade de reproduzir dados comprimidos de áudio e vídeo em conjunto. </p>
+
+
+
+<div class="figure" style="width:320px; margin:1em 0 0 20px;padding-left:2em;">
+<img style="float:right; margin:0 1em 1em 2em" src="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png" srcset="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png 2x" alt="" width="300" />
+<p class="img-caption">Os usuários têm uma visualização unificada de seus apps pessoais e de trabalho, que têm selos para facilitar a identificação.</p>
+</div>
+
+
+<h2 id="Work">Android no local de trabalho</h2>
+
+<p>Para ativar a opção de trazer seu próprio dispositivo em ambientes corporativos, um novo <a href="{@docRoot}about/versions/android-5.0.html#Enterprise">processo de aprovisionamento gerenciado</a> cria um perfil de trabalho seguro no dispositivo. No lançador, os apps são mostrados com o selo de Trabalho para indicar que o app e seus dados são administrados no perfil de trabalho por um administrador de TI.</p>
+
+<p>As notificações do perfil de trabalho e do perfil pessoal são acessadas em uma visualização unificada. Os dados de cada perfil são sempre mantidos separados e seguros entre si, incluindo quando o mesmo app é usado por ambos os perfis.</p>
+
+<p>Para dispositivos de propriedade de uma empresa, os administradores de TI podem iniciar com um novo dispositivo e configurá-lo com um <a href="{@docRoot}about/versions/android-5.0.html#DeviceOwner">proprietário do dispositivo</a>. Os empregadores podem emitir esses dispositivos com um app de proprietário do dispositivo já instalado que pode definir configurações globais do dispositivo.</p>
+
+
+
+<h2 id="ScreenCapture">Compartilhamento e captura de tela</h2>
+
+<p>O Android 5.0 permite adicionar recursos de captura e compartilhamento de tela a seu app. </p>
+
+<p>Com a permissão do usuário, é possível capturar vídeo não seguro na tela e exibi-lo pela rede, se for de sua escolha.</p>
+
+
+<h2 id="Sensors">Novos tipos de sensores</h2>
+
+<p>No Android 5.0, um novo sensor com <strong>detector de inclinação</strong> ajuda a melhorar o reconhecimento de atividades em dispositivos compatíveis, e um <strong>sensor de atividade cardíaca</strong> faz o relatório da frequência cardíaca do usuário que toca no dispositivo. </p>
+
+<p>Novos <strong>sensores compostos de interação</strong> agora estão disponíveis para detectar interações especiais, como gestos de <em>acordar</em>, <em>pegar</em> e <em>olhar rapidamente</em>.</p>
+
+
+
+<h2 id="WebView">WebView do Chromium</h2>
+
+<div style="float:right;margin:1em 2em 1em 2em;">
+ <img src="/images/kk-chromium-icon.png" alt="" height="160" style="margin-bottom:0em;">
+</div>
+
+<p>A versão inicial para Android 5.0 inclui uma versão do Chromium para {@link android.webkit.WebView} com base na versão M37 do Chromium, adicionando suporte a <strong>WebRTC</strong>, <strong>WebAudio</strong> e <strong>WebGL</strong>. </p>
+
+<p>O Chromium M37 também inclui suporte nativo a todas as especificações de <strong>Componentes Web</strong>: elementos personalizados, DOM de sombra, Importações de HTML e modelos. Isso significa que é possível usar o <a href="http://polymer-project.org/">Polymer</a> e seus <a href="https://www.polymer-project.org/docs/elements/material.html">elementos de material design</a> em um WebView sem a necessidade de polyfills.</p>
+
+<p>Embora o WebView seja baseado no Chromium desde o Android 4.4, a camada do Chromium agora é atualizável no Google Play.</p>
+
+<p>À medida que novas versões do Chromium são disponibilizadas, os usuários podem atualizar a partir do Google Play para garantir que recebam as mais recentes melhorias e correções de bugs para WebView, oferecendo as APIs da Web e correções de bug mais recentes aos apps que usam o WebView no Android 5.0 e posterior.</p>
+
+
+
+<h2 id="Accessibility">Acessibilidade e entrada</h2>
+
+<p>Novas APIs de acessibilidade podem recuperar informações detalhadas sobre as propriedades das janelas na tela. Com elas, usuários com problemas de visão podem interagir e definir ações de entrada padrão ou personalizadas para elementos da interface do usuário.</p>
+
+<p>Novas APIs do editor de Método de entrada (IME) permitem trocar com mais rapidez para outros IMEs diretamente no método de entrada.</p>
+
+
+
+<h2 id="Battery">Ferramentas para a criação de apps com eficiência de bateria</h2>
+
+<p>Novas APIs de <strong>agendamento de tarefas</strong> permitem otimizar a vida útil da bateria adiando tarefas para que o sistema as execute mais tarde ou em condições específicas, como quando o dispositivo é carregado ou está conectado ao Wi-Fi.</p>
+
+<p>Um novo comando <code>dumpsys batterystats</code> gera <strong>Estatísticas de uso da bateria</strong> que podem ser utilizadas para entender o uso de energia em todo o sistema e o impacto de seu app na bateria do dispositivo. É possível ver um histórico dos eventos de energia, o uso aproximado de energia por UID e por componente do sistema, entre outros.</p>
+
+<img src="{@docRoot}images/versions/battery_historian.png" srcset="{@docRoot}images/versions/battery_historian@2x.png 2x" alt="" width="760" height="462" />
+<p class="img-caption">O Battery Historian é uma nova ferramenta que converte as estatísticas de <code>dumpsys batterystats</code> em uma visualização para depuração da bateria. Você pode encontrá-lo em <a href="https://github.com/google/battery-historian">https://github.com/google/battery-historian</a>.</p>
diff --git a/docs/html-intl/intl/ru/about/versions/android-5.0.jd b/docs/html-intl/intl/ru/about/versions/android-5.0.jd
new file mode 100644
index 0000000..5dbbac8
--- /dev/null
+++ b/docs/html-intl/intl/ru/about/versions/android-5.0.jd
@@ -0,0 +1,636 @@
+page.title=API для Android 5.0
+excludeFromSuggestions=true
+sdk.platform.version=5.0
+sdk.platform.apiLevel=21
+@jd:body
+
+
+<div id="qv-wrapper">
+<div id="qv">
+
+<h2>Содержание документа<a href="#" onclick="hideNestedItems('#toc44',this);return false;" class="header-toggle"> <span class="more">подробнее</span> <span class="less" style="display:none">свернуть</span></a></h2>
+
+<ol id="toc44" class="hide-nested">
+ <li><a href="#ApiLevel">Обновление целевого уровня API</a></li>
+ <li><a href="#Behaviors">Важные функциональные изменения</a>
+ <ol>
+ <li><a href="#ART">Если вы не тестировали свое приложение в новой среде выполнения Android (ART)...</a></li>
+ <li><a href="#BehaviorNotifications">Если в приложение нужно добавить уведомления...</a></li>
+ <li><a href="#BehaviorMediaControl">Если в приложении используется RemoteControlClient...</a></li>
+<li><a href="#BehaviorGetRecentTasks">Если в приложении используется метод getRecentTasks()...</a></li>
+<li><a href="#64BitSupport">Если вы используете инструмент разработчика Android Native Development Kit (NDK)...</a></li>
+<li><a href="#BindService">Если ваше приложение связано с определенным сервисом...</a></li>
+<li><a href="#BehaviorWebView">Если в приложении используется сервис WebView...</a></li>
+ </ol>
+ </li>
+ <li><a href="#UI">Пользовательский интерфейс</a>
+ <ol>
+ <li><a href="#MaterialDesign">Material Design</a></li>
+ <li><a href="#Recents">Одновременный просмотр документов и процессов на экране</a></li>
+ <li><a href="#WebView">Обновления WebView</a></li>
+ <li><a href="#ScreenCapture">Сохранение и отправка данных с экрана</a></li>
+ </ol>
+ </li>
+ <li><a href="#Notifications">Уведомления</a>
+ <ol>
+ <li><a href="#LockscreenNotifications">Уведомления на экране блокировки</a></li>
+ <li><a href="#NotificationsMetadata">Метаданные уведомлений</a></li>
+ </ol>
+ </li>
+ <li><a href="#Graphics">Графика</a>
+ <ol>
+ <li><a href="#OpenGLES-3-1">Поддержка OpenGL ES 3.1</a></li>
+ <li><a href="#AndroidExtensionPack">Набор расширений для Android</a></li>
+ </ol>
+ </li>
+ <li><a href="#Media">Мультимедиа</a>
+ <ol>
+ <li><a href="#Camera-v2">API для расширенных возможностей камеры</a></li>
+ <li><a href="#AudioPlayback">Воспроизведение аудио</a></li>
+ <li><a href="#MediaPlaybackControl">Управление воспроизведением мультимедиа</a></li>
+ <li><a href="#MediaBrowsing">Поиск и просмотр мультимедиа</a></li>
+ </ol>
+ </li>
+ <li><a href="#Storage">Хранение данных</a>
+ <ol>
+ <li><a href="#DirectorySelection">Выбор каталогов</a></li>
+ </ol>
+ </li>
+ <li><a href="#Wireless">Беспроводные сети и подключения</a>
+ <ol>
+ <li><a href="#Multinetwork">Подключения к нескольким сетям</a></li>
+ <li><a href="#BluetoothBroadcasting">Передача данных по Bluetooth</a></li>
+ <li><a href="#NFCEnhancements">Новые возможности NFC</a></li>
+ </ol>
+ </li>
+ <li><a href="#Power">Project Volta</a>
+ <ol>
+ <li><a href="#JobScheduler">Планирование заданий</a></li>
+ <li><a href="#PowerMeasurementTools">Инструменты для разработчиков (использование батареи)</a>
+ </ol>
+ </li>
+ <li><a href="#Enterprise">Android для работы и учебы</a>
+ <ol>
+ <li><a href="#ManagedProvisioning">Контролируемые профили</a></li>
+ <li><a href="#DeviceOwner">Владелец устройства</a></li>
+ <li><a href="#ScreenPinning">Блокировка в приложении</a></li>
+ </ol>
+ </li>
+ <li><a href="#System">Система</a>
+ <ol>
+ <li><a href="#AppUsageStatistics">Статистика по использованию приложений</a></li>
+ </ol>
+ </li>
+ <li><a href="#Printing">Инфраструктура печати</a>
+ <ol>
+ <li><a href="#PDFRender">Обработка PDF как растрового изображения</a></li>
+ </ol>
+ </li>
+ <li><a href="#TestingA11y">Тестирование и доступность</a>
+ <ol>
+ <li><a href="#TestingA11yImprovements">Новые возможности тестирования и оценки доступности</a></li>
+ </ol>
+ </li>
+ <li><a href="#IME">Редактор способов ввода (IME)</a>
+ <ol>
+ <li><a href="#Switching">Упрощенное переключение между языками ввода</a></li>
+ </ol>
+ </li>
+ <li><a href="#Manifest">Объявление манифеста</a>
+ <ol>
+ <li><a href="#ManifestFeatures">Объявляемые обязательные функции</a></li>
+ <li><a href="#Permissions">Разрешения для пользователей</a></li>
+ </ol>
+ </li>
+</ol>
+
+<h2>API Differences</h2>
+<ol>
+<li><a href="{@docRoot}sdk/api_diff/21/changes.html">API level 20 to 21 &raquo;</a> </li>
+<li><a href="{@docRoot}sdk/api_diff/preview-21/changes.html">L Developer Preview to 21 &raquo;</a> </li>
+</ol>
+
+<h2>See Also</h2>
+<ol>
+<li><a href="{@docRoot}about/versions/android-5.0-changes.html">Android 5.0 Behavior Changes</a> </li>
+<li><a href="{@docRoot}about/versions/lollipop.html">Android Lollipop Highlights</a> </li>
+</ol>
+
+</div>
+</div>
+
+<p>Уровень API: {@sdkPlatformApiLevel}</p>
+
+<p>В Android 5.0 (<a href="{@docRoot}reference/android/os/Build.VERSION_CODES.html#LOLLIPOP">Lollipop</a>) реализованы новые функции как для пользователей, так и для разработчиков приложений. Из этой статьи вы узнаете о самых важных особенностях новых API.</p>
+
+<p>Чтобы получить общее представление о новых функциях платформы, прочитайте краткий обзор <a href="{@docRoot}about/versions/lollipop.html">Android Lollipop</a>.</p>
+
+
+<h3 id="Start">Приступая к разработке</h3>
+
+<p>Чтобы создавать приложения для Android 5.0, вам потребуется <a href="{@docRoot}sdk/index.html">Android SDK</a>. Воспользуйтесь <a href="{@docRoot}tools/help/sdk-manager.html">Менеджером SDK</a>, чтобы загрузить платформу SDK для Android 5.0 и образы системы.</p>
+
+
+<h3 id="ApiLevel">Обновление целевого уровня API</h3>
+
+<p>Чтобы оптимизировать приложение для устройств под управлением Android {@sdkPlatformVersion}, настройте <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> на уровень <code>"{@sdkPlatformApiLevel}"</code>, установите приложение на образ системы Android {@sdkPlatformVersion}, проверьте его, а затем опубликуйте обновленную версию.</p>
+
+<p>Вы можете воспользоваться API Android {@sdkPlatformVersion} и для работы со старыми версиями. Для этого добавьте соответствующие данные в код, проверяющий уровень API перед выполнением функций, которые могут не поддерживаться <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a>. Подробнее о том, как обеспечить совместимость с предыдущими версиями, читайте <a href="{@docRoot}training/basics/supporting-devices/platforms.html">здесь</a>.</p>
+
+<p>Сведения об уровнях API представлены в <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">этой статье</a>.</p>
+
+<h2 id="Behaviors">Важные функциональные изменения</h2>
+
+<p>Если вы уже публиковали приложения для Android, учтите, что изменения в версии 5.0 могут повлиять на их работу.</p>
+
+<h3 id="ART">Если вы не тестировали свое приложение в новой среде выполнения Android (ART)...</h3>
+
+<p>В версии 4.4 была представлена новая экспериментальная среда выполнения Android (ART). Ее можно было выбирать при необходимости, а по умолчанию использовалось решение Dalvik. Для Android 5.0 ART&nbsp;– среда выполнения по умолчанию.</p>
+
+<p>Подробнее о новых функциях ART читайте <a href="https://source.android.com/devices/tech/dalvik/art.html">здесь</a>. Вот некоторые из них:</p>
+
+<ul>
+ <li>Предварительная компиляция (AOT).</li>
+ <li>Более эффективная очистка памяти.</li>
+ <li>Улучшенные методы отладки.</li>
+</ul>
+
+<p>Большинство приложений для Android не потребуют никаких изменений при переходе на ART. Однако некоторые функции, действовавшие в Dalvik, поддерживаться не будут. Подробнее об этом читайте в разделе, который посвящен <a href="{@docRoot}guide/practices/verifying-apps-art.html">проверке работы приложения в среде выполнения ART</a>. Будьте особо внимательны в следующих случаях:</p>
+
+<ul>
+ <li>Ваше приложение использует Java Native Interface (JNI) для выполнения кода C/C++.</li>
+ <li>Вы применяете инструменты для разработчиков, позволяющие создавать нестандартный код (в том числе для обфускации).</li>
+ <li>Ваши технологии нельзя применять, если используется очистка памяти с уплотнением. ART в настоящее время не поддерживает эту функцию, однако она разрабатывается в проекте ПО с открытым исходным кодом для Android.</li>
+</ul>
+
+<h3 id="BehaviorNotifications">Если в приложение нужно добавить уведомления...</h3>
+
+<p>При создании уведомлений учитывайте нововведения в Android 5.0. Подробнее об оповещениях для Android 5.0 и выше читайте в соответствующем <a href="{@docRoot}design/patterns/notifications.html">руководстве</a>.
+</p>
+
+<h4 id="NotificationsMaterialDesignStyle">Концепция Material Design</h4>
+<p>Уведомления выводятся с темным текстом на белом (или очень светлом) фоне. Это хорошо смотрится при использовании новых виджетов с текстурой. Убедитесь, что все ваши уведомления правильно выглядят в новой цветовой схеме. Если они отображаются некорректно, исправьте их:</p>
+
+<ul>
+ <li>Используйте метод {@link android.app.Notification.Builder#setColor(int) setColor()}, чтобы указать цвет фона значка. </li>
+ <li>Обновите или удалите ресурсы, в которых задействован цвет. Система обрабатывает только альфа-каналы как для значков действий, так и для основного значка уведомления. Учитывайте это. Система отображает значки уведомлений белым цветом, а значки действий&nbsp;– темно-серым.</li>
+</ul>
+
+<h4 id="NotificationsSoundVibration">Звук и вибрация</h4>
+<p>Если в настоящее время вы добавляете звуки и вибрацию в уведомления с помощью классов {@link android.media.Ringtone}, {@link android.media.MediaPlayer} или {@link android.os.Vibrator}, удалите этот код. Тогда система будет правильно обрабатывать уведомления с учетом <em>приоритета</em>. Чтобы добавить звуки и вибрацию, используйте методы {@link android.app.Notification.Builder}.</p>
+
+<p>Чтобы войти в новый режим приоритета, выберите на устройстве настройку {@link android.media.AudioManager#RINGER_MODE_SILENT RINGER_MODE_SILENT}. При выборе настроек {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_NORMAL} или {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_VIBRATE} режим приоритета отключается.</p>
+
+<p>Раньше в системе Android для управления звуком на планшетах использовался основной поток {@link android.media.AudioManager#STREAM_MUSIC STREAM_MUSIC}. В Android 5.0 {@link android.media.AudioManager#STREAM_RING STREAM_RING} и {@link android.media.AudioManager#STREAM_NOTIFICATION STREAM_NOTIFICATION} будут поддерживаться как для телефонов, так и для планшетов.</p>
+
+<h4 id="NotificationsLockscreenVisibility">Элементы на экране блокировки</h4>
+<p>По умолчанию в Android 5.0 уведомления показываются на экране блокировки. Однако пользователи могут включить функцию защиты личных данных. В таком случае система будет автоматически редактировать текст уведомлений. Чтобы настроить показ уведомлений, содержащих личные данные, используйте элемент {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()}.</p>
+<p>Если уведомление не содержит личных данных или вы хотите разрешить воспроизведение мультимедиа в нем, вызовите метод {@link android.app.Notification.Builder#setVisibility(int) setVisibility()} и задайте видимость уведомления как {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}.
+</p>
+
+<h4 id="NotificationsMediaPlayback">Воспроизведение мультимедиа</h4>
+<p>Если в ваших уведомлениях присутствуют сведения о воспроизведении мультимедиа или передаче данных, рекомендуем использовать новый шаблон {@link android.app.Notification.MediaStyle} вместо объекта {@link android.widget.RemoteViews.RemoteView}. Какой бы вариант вы ни выбрали, убедитесь, что для отображения уведомления выбран вариант {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}. Тогда управление мультимедиа будет доступно на экране блокировки. Учтите, что в Android 5.0 и последующих версиях будет прекращен показ объектов {@link android.media.RemoteControlClient} на экране блокировки. Подробнее читайте в разделе <a href="#BehaviorMediaControl">Если ваше приложение использует RemoteControlClient</a>.</p>
+
+<h4 id="NotificationsHeadsup">Всплывающие уведомления</h4>
+<p>Теперь уведомления могут отображаться в небольшом всплывающем окне, если устройство активно (то есть разблокировано, а экран включен). Они почти аналогичны компактным. Разница только в том, что во всплывающих окнах есть кнопки для выполнения действий. Пользователь может выполнить действие или закрыть уведомление, не покидая приложения.</p>
+
+<p>Всплывающие уведомления появляются в следующих ситуациях:</p>
+
+<ul>
+ <li>Пользователь выполняет действия в полноэкранном режиме (приложение использует {@link android.app.Notification#fullScreenIntent}).</li>
+ <li>Уведомление имеет высокий приоритет, используется звук или вибрация.</li>
+</ul>
+
+<p>Если при таких условиях в вашем приложении будут появляться всплывающие уведомления, убедитесь, что они отображаются корректно.</p>
+
+<h3 id="BehaviorMediaControl">Если в приложении используется RemoteControlClient...</h3>
+<p>Класс {@link android.media.RemoteControlClient} теперь не поддерживается. Как можно скорее перейдите на API {@link android.media.session.MediaSession}.</p>
+
+<p>На экране блокировки в Android 5.0 не отображаются кнопки управления передачей данных для {@link android.media.session.MediaSession} или {@link android.media.RemoteControlClient}. Вместо этого система показывает кнопки управления воспроизведением мультимедиа. Теперь вам проще выбрать их варианты, которые будут удобны как на заблокированном, так и разблокированном устройстве.</p>
+
+<p>В Android 5.0 для этого имеется новый шаблон {@link android.app.Notification.MediaStyle}. {@link android.app.Notification.MediaStyle} конвертирует действия, добавленные с помощью {@link android.app.Notification.Builder#addAction(int, java.lang.CharSequence, android.app.PendingIntent) Notification.Builder.addAction()}, в компактные кнопки для уведомлений с возможностью воспроизведения мультимедиа. Чтобы сообщить системе о том, что уведомление связано с активным сеансом воспроизведения мультимедиа, необходимо передать токен сеанса в метод {@link android.app.Notification.MediaStyle#setMediaSession(android.media.session.MediaSession.Token) setSession()}.</p>
+
+<p>Убедитесь, что выбран вариант отображения {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC} и уведомление будет появляться на экране блокировки, даже если включен режим безопасности. Подробнее об уведомлениях на экране блокировки читайте <a href="#LockscreenNotifications">здесь</a>.</p>
+
+<p>Если ваше приложение работает на платформе Android <a href="{@docRoot}tv/index.html">TV</a> или <a href="{@docRoot}wear/index.html">Wear</a>, внедрите класс {@link android.media.session.MediaSession}. Он поддерживает показ кнопок для управления воспроизведением. Если приложение должно получать информацию о действиях с кнопками на устройствах Android, необходимо также внедрить {@link android.media.session.MediaSession}.</p>
+
+<h3 id="BehaviorGetRecentTasks">Если в приложении используется метод getRecentTasks()...</h3>
+
+<p>В Android 5.0 появилась новая функция <em>одновременной работы с документами и процессами</em> (см. <a href="#Recents">ниже</a>). Метод {@link android.app.ActivityManager#getRecentTasks ActivityManager.getRecentTasks()} больше не поддерживается. Чтобы обеспечить совместимость со старыми версиями, этот метод по-прежнему возвращает небольшое количество данных. Например, он вызывает собственные задачи приложения и некоторые другие задачи (например, переход на главную страницу). Если в вашем приложении применяется этот метод, замените его на {@link android.app.ActivityManager#getAppTasks() getAppTasks()}.</p>
+
+<h3 id="64BitSupport">Если вы используете Android Native Development Kit (NDK)...</h3>
+
+<p>Android 5.0 теперь поддерживает как 32- так и 64-разрядные системы. Поддержка 64-разрядных систем увеличивает производительность и расширяет пространство адресов. Также при этом повышается скорость работы OpenSSL для криптографии. Кроме того, в новом выпуске используются API NDK для мультимедиа, а также поддерживается OpenGL ES (GLES) 3.1.</p>
+
+<p>Чтобы воспользоваться поддержкой 64-разрядных систем в Android 5.0, скачайте и установите NDK версии 10c со страницы <a href="{@docRoot}tools/sdk/ndk/index.html">Android NDK</a>. Подробнее о важных изменениях и исправленных ошибках в NDK читайте в <a href="{@docRoot}tools/sdk/ndk/index.html#Revisions">примечаниях к выпуску</a> 10с.</p>
+
+<h3 id="BindService">Если ваше приложение связано с определенным сервисом...</h3>
+
+<p>Метод {@link android.content.Context#bindService(android.content.Intent, android.content.ServiceConnection, int) Context.bindService()} теперь требует явного использования {@link android.content.Intent}, а при неявном выполняется исключение. Чтобы обеспечить безопасность приложения, используйте явную цель при запуске или связывании {@link android.app.Service}. Не применяйте фильтры цели для сервиса.</p>
+
+<h3 id="BehaviorWebView">Если в приложении используется сервис WebView...</h3>
+
+<p>Android 5.0 изменяет функционирование вашего приложения по умолчанию.</p>
+<ul>
+<li><strong>Если приложение ориентировано на API уровня 21 или выше...</strong>
+ <ul>
+ <li>Система по умолчанию блокирует <a href="https://developer.mozilla.org/en-US/docs/Security/MixedContent" class="external-link">смешанный контент</a> и сторонние файлы cookie. Чтобы разрешить передачу таких данных, используйте соответственно методы {@link android.webkit.WebSettings#setMixedContentMode(int) setMixedContentMode()} и {@link android.webkit.CookieManager#setAcceptThirdPartyCookies(android.webkit.WebView, boolean) setAcceptThirdPartyCookies()}.</li>
+ <li>Теперь система целенаправленно выбирает разделы HTML-документа для извлечения. Такой подход уменьшает расход памяти и повышает производительность. Если вы хотите обработать весь документ сразу, отключите этот метод оптимизации путем вызова {@link android.webkit.WebView#enableSlowWholeDocumentDraw()}.</li>
+ </ul>
+</li>
+<li><strong>Если приложение ориентировано на API ниже уровня 21</strong>, система будет поддерживать смешанный контент и внешние файлы cookie, а также обрабатывать документы полностью.</li>
+</ul>
+
+<h2 id="UI">Пользовательский интерфейс</h2>
+
+<h3 id="MaterialDesign">Material Design</h3>
+
+<p>В будущей версии Android поддерживается новая концепция <em>Material Design</em>. Вы сможете создавать приложения с обновленным динамичным дизайном и органично меняющимися элементами интерфейса. Поддерживаются следующие функции:</p>
+
+<ul>
+
+ <li>тема Material;</li>
+ <li>тени при просмотре;</li>
+ <li>виджет {@link android.support.v7.widget.RecyclerView};</li>
+ <li>графическая анимация и эффекты;</li>
+ <li>анимация Material Design и эффекты отклика на действия;</li>
+ <li>инструменты для настройки свойств с учетом статуса просмотра;</li>
+ <li>настраиваемые виджеты для интерфейса и панели с цветовыми палитрами;</li>
+ <li>анимированная и неанимированная векторная графика на основе XML.</li>
+</ul>
+
+<p>Подробнее о том, как добавить элементы этого дизайна в свое приложение, читайте в разделе <a href="{@docRoot}training/material/index.html">Material Design</a>.</p>
+
+<h3 id="Recents">Одновременный просмотр документов и процессов на экране</h3>
+
+<p>В предыдущих выпусках на <a href="{@docRoot}guide/components/recents.html">экране недавно использованных функций</a> могла отображаться только одна задача для каждого приложения. Теперь там могут быть представлены и несколько задач, если вы одновременно работали с несколькими документами. Эта функция обеспечивает многозадачность, позволяя быстро переключаться между отдельными действиями и документами в списке недавно использованных. Одновременно выполняемыми задачами могут быть вкладки, открытые в веб-браузере, документы, одновременные состязания в игре или чаты в социальном приложении. Приложение может управлять задачами с помощью класса {@link android.app.ActivityManager.AppTask}.</p>
+
+<p>Чтобы вставить логический перерыв, после которого система будет воспринимать действие как новое, используйте {@link android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT} при запуске действия с помощью {@link android.app.Activity#startActivity(android.content.Intent) startActivity()}. Также можно выбрать для атрибута элемента <a href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a> {@code documentLaunchMode} значение {@code "intoExisting"} или {@code "always"} непосредственно в манифесте.</p>
+
+<p>Чтобы ограничить количество данных на экране, можно задать максимальное число задач из приложения, которые будут там показываться. Для этого укажите для атрибута <a href="{@docRoot}guide/topics/manifest/application-element.html">&lt;application&gt;</a> значение {@link android.R.attr#maxRecents android:maxRecents}. В настоящее время можно указать до 50&nbsp;задач на пользователя (25 для устройств с небольшим объемом ОЗУ).</a></p>
+
+<p>Вы можете настроить сохранение задач на экране недавно использованных даже после перезагрузки. Для управления временем отображения применяется атрибут <a href="{@docRoot}reference/android/R.attr.html#persistableMode">android:persistableMode</a>. Вы также можете изменить визуальное отображение действия, то есть его цвет, ярлык и значок. Для этого следует вызвать метод {@link android.app.Activity#setTaskDescription(android.app.ActivityManager.TaskDescription) setTaskDescription()}.</p>
+
+<h3 id="WebView">Обновления WebView</h3>
+<p>В Android 5.0 обновлен процесс внедрения {@link android.webkit.WebView} для Chromium M37. Он стал более стабильным и безопасным, ошибки были устранены. Строка агента пользователя, которая по умолчанию использовалась для {@link android.webkit.WebView}, в Android 5.0 содержит номер версии (37.0.0.0).</p>
+
+<p>В этом выпуске представлен класс {@link android.webkit.PermissionRequest}, с помощью которого приложение обеспечивает {@link android.webkit.WebView} доступ к защищенным ресурсам, таким как камера и микрофон. Это делается с помощью инструментов API, например <a href="https://developer.mozilla.org/en-US/docs/NavigatorUserMedia.getUserMedia" class="external-link">getUserMedia()</a>. У вашего приложения должны быть все разрешения от Android на доступ к этим ресурсам. Тогда оно сможет передать их элементу {@link android.webkit.WebView}.</p>
+
+<p>Новый метод <code><a href="{@docRoot}reference/android/webkit/WebChromeClient.html#onShowFileChooser(android.webkit.WebView, android.webkit.ValueCallback<android.net.Uri[]>, android.webkit.WebChromeClient.FileChooserParams)">onShowFileChooser()</a></code> позволяет добавить в {@link android.webkit.WebView} поле для ввода, чтобы можно было выбирать файлы (изображения и&nbsp;т.&nbsp;п.) на устройстве Android.</p>
+
+<p>Также в этом выпуске поддерживаются открытые стандарты <a href="http://webaudio.github.io/web-audio-api/" class="external-link">WebAudio</a>, <a href="https://www.khronos.org/webgl/" class="external-link">WebGL</a> и <a href="http://www.webrtc.org/" class="external-link">WebRTC</a>. Подробнее о новых функциях в этом выпуске читайте в разделе <a href="https://developer.chrome.com/multidevice/webview/overview" class="external-link">WebView для Android</a>.</p>
+
+<h3 id="ScreenCapture">Сохранение и отправка данных с экрана</h3>
+<p>Android 5.0 поддерживает функцию сохранения данных с экрана и отправки их другим пользователям. Добавить ее в свое приложение можно с помощью нового API {@link android.media.projection}. Эта функция может быть очень полезной, например в приложениях для видеоконференций.</p>
+
+<p>Новый метод {@link android.media.projection.MediaProjection#createVirtualDisplay(java.lang.String, int, int, int, int, android.view.Surface, android.hardware.display.VirtualDisplay.Callback, android.os.Handler) createVirtualDisplay()} позволяет приложению сохранять снимок главного экрана (с дисплея по умолчанию) как объект {@link android.view.Surface}, который затем может быть передан по сети. С помощью этого API нельзя настроить сохранение защищенного контента и системных аудиоданных. Чтобы начать запись данных с экрана, приложение должно запросить разрешение пользователя с помощью {@link android.content.Intent} и метода {@link android.media.projection.MediaProjectionManager#createScreenCaptureIntent()}.</p>
+
+<p>Посмотреть, как используется новый API, можно в примере проекта (см. класс {@code MediaProjectionDemo}).</p>
+
+<h2 id="Notifications">Уведомления</h2>
+
+<h3 id="LockscreenNotifications">Уведомления на экране блокировки</h3>
+<p>На экране блокировки в Android 5.0 могут появляться уведомления. Чтобы при этом в них не отображались персональные данные, достаточно выбрать соответствующую опцию в <em>Настройках</em>.</p>
+
+<p>Если показ таких сведений запрещен, приложение автоматически выявляет их и скрывает из уведомления. Для настройки уведомлений вызовите {@link android.app.Notification.Builder#setVisibility(int) setVisibility()} и укажите одно из следующих значений:</p>
+
+<ul>
+<li>{@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}: показывать основные сведения, такие как значок, но скрывать все остальные сведения в уведомлении.</li>
+<li>{@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}: показывать уведомление полностью.</li>
+<li>{@link android.app.Notification#VISIBILITY_SECRET VISIBILITY_SECRET}: не показывать ничего, кроме значка уведомления.</li>
+</ul>
+
+<p>Если выбрано значение {@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}, вы также можете предоставить отредактированную версию уведомления, не содержащую личных данных. Например, приложение для отправки SMS может показывать уведомление с текстом "У вас 3 новых сообщения", но скрывать содержание и отправителей. Чтобы добавить альтернативное уведомление, сначала создайте замену с помощью {@link android.app.Notification.Builder}. При создании объекта уведомления с личными данными добавьте его замену, используя метод {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()}.</p>
+
+<h3 id="NotificationsMetadata">Метаданные уведомлений</h3>
+<p>Android 5.0 использует метаданные, связанные с уведомлениями в приложениях, чтобы сортировать их. Для настройки метаданных вызовите следующие методы в {@link android.app.Notification.Builder} при создании уведомления:</p>
+
+<ul>
+<li>{@link android.app.Notification.Builder#setCategory(java.lang.String) setCategory()}: сообщать системе, как обрабатывать уведомления, если устройство находится в режиме <em>приоритета</em> (например, если это уведомление о звонке, сообщении или будильнике).
+<li>{@link android.app.Notification.Builder#setPriority(int) setPriority()}: помечать уведомление как более или менее важное. Уведомления с полем приоритета {@link android.app.Notification#PRIORITY_MAX PRIORITY_MAX} или {@link android.app.Notification#PRIORITY_HIGH PRIORITY_HIGH} отображаются в маленьком всплывающем окне, если для них также настроены звуки и вибрация.</li>
+<li>{@link android.app.Notification.Builder#addPerson(java.lang.String) addPerson()}: возможность указать пользователей, связанных с уведомлением. Приложение может подать системе сигнал о том, что следует объединить уведомления от определенных пользователей или присвоить им более высокий рейтинг.</li>
+</ul>
+
+<h2 id="Graphics">Графика</h2>
+
+<h3 id="OpenGLES-3-1">Поддержка OpenGL ES версии 3.1</h3>
+<p>Android 5.0 поддерживает интерфейсы Java и OpenGL ES 3.1. Примеры новых функций OpenGL ES 3.1:</p>
+
+<ul>
+<li>вычислительные шейдеры;
+<li>отдельные объекты для шейдеров;
+<li>непрямые команды рисования;
+<li>мультисэмплинг и трафаретные шаблоны;
+<li>усовершенствованный язык шейдеров;
+<li>расширения для продвинутых режимов наложения и отладки;
+<li>обратная совместимость с OpenGL ES 2.0 и 3.0.
+</ul>
+
+<p>Интерфейс Java для OpenGL ES 3.1 на Android обеспечивается посредством элемента {@link android.opengl.GLES31}. При использовании OpenGL ES 3.1 убедитесь, что этот элемент объявлен в файле манифеста с помощью тега <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> и атрибута {@code android:glEsVersion}. Пример:</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:glEsVersion="0x00030001" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<p>Подробнее об использовании OpenGL ES (в том числе об определении поддерживаемой версии), читайте в соответствующем <a href="{@docRoot}guide/topics/graphics/opengl.html">руководстве по API</a>.</p>
+
+<h3 id="AndroidExtensionPack">Набор расширений для Android</h3>
+
+<p>Помимо OpenGL ES 3.1 в этом выпуске представлен набор расширений с интерфейсами Java и поддержкой продвинутых графических функций. Android воспринимает эти расширения как единый набор. (При наличии расширения {@code ANDROID_extension_pack_es31a} ваше приложение может зарегистрировать все расширения в наборе и включить шейдеры с помощью одного оператора {@code #extension}.)</p>
+
+<p>Набор расширений поддерживает следующие функции:</p>
+
+<ul>
+<li>Гарантированная поддержка пиксельных шейдеров для буферов, изображений и атомарных переменных (в OpenGL ES 3.1 пиксельные шейдеры использовать не обязательно).</li>
+<li>Тесселяция и геометрические шейдеры.</li>
+<li>Формат сжатия текстур ASTC (LDR).</li>
+<li>Посэмпловая интерполяция и затенение.</li>
+<li>Различные режимы наложения для каждого цвета в буфере кадра.</li>
+</ul>
+
+<p>Интерфейс Java для набора разрешений поддерживается с помощью {@link android.opengl.GLES31Ext}. В манифесте приложения вы можете объявить, что возможна установка только на устройства с поддержкой набора разрешений. Пример:</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:name=“android.hardware.opengles.aep”
+ android:required="true" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<h2 id="Media">Мультимедиа</h2>
+
+<h3 id="Camera-v2">API для расширенных возможностей камеры</h3>
+
+<p>Android 5.0 поддерживает новый API <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">android.hardware.camera2</a> для создания качественных фотографий и их последующей обработки. Теперь вы можете получать доступ к камерам в системе с помощью {@link android.hardware.camera2.CameraManager#getCameraIdList() getCameraIdList()} и подключаться к ним, используя {@link android.hardware.camera2.CameraManager#openCamera(java.lang.String, android.hardware.camera2.CameraDevice.StateCallback, android.os.Handler) openCamera()}. Чтобы начать фотосъемку, создайте {@link android.hardware.camera2.CameraCaptureSession} и укажите объекты {@link android.view.Surface} для отправки сделанных фото. {@link android.hardware.camera2.CameraCaptureSession} можно настроить на однократные или многократные снимки.</p>
+
+<p>Чтобы получать уведомления при создании новых снимков, внедрите обработчик событий {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} и настройте его на соответствующий запрос. После того как система выполнит запрос на создание снимка, обработчик {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} получит вызов {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback#onCaptureCompleted(android.hardware.camera2.CameraCaptureSession, android.hardware.camera2.CaptureRequest, android.hardware.camera2.TotalCaptureResult) onCaptureCompleted()} и передаст вам метаданные изображения в виде {@link android.hardware.camera2.CaptureResult}.</p>
+
+<p>С помощью класса {@link android.hardware.camera2.CameraCharacteristics} приложение может определять, какие свойства камеры доступны на устройстве. Свойства объекта {@link android.hardware.camera2.CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL INFO_SUPPORTED_HARDWARE_LEVEL} позволяют получать данные о функциональности камеры.</p>
+
+<ul>
+ <li>Все устройства поддерживают ПО не ниже уровня {@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY}. Его свойства примерно соответствуют устаревшему API {@link android.hardware.Camera}.</li>
+ <li>Устройства, которые поддерживают ПО уровня {@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_FULL INFO_SUPPORTED_HARDWARE_LEVEL_FULL}, позволяют вручную управлять съемкой и обработкой изображений в высоком разрешении и с высокой кадровой частотой.</li>
+</ul>
+
+<p>Подробнее об использовании обновленного API <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">камеры</a> см. в примерах {@code Camera2Basic} и {@code Camera2Video} в этом выпуске.</p>
+
+<h3 id="AudioPlayback">Воспроизведение аудио</h3>
+<p>В этом выпуске представлены следующие изменения {@link android.media.AudioTrack}:</p>
+<ul>
+ <li>Приложение теперь может передавать аудиоданные в формате с плавающей точкой ({@link android.media.AudioFormat#ENCODING_PCM_FLOAT ENCODING_PCM_FLOAT}). Это расширяет динамический диапазон, обеспечивает точность звука и более широкое звуковое пространство. Арифметика с плавающей точкой особенно полезна при промежуточных вычислениях. Конечные точки воспроизведения используют для аудиоданных формат целых чисел и более низкую битовую глубину. (В Android 5.0 внутренний конвейер пока ещё не полностью поддерживает формат с плавающей точкой.)
+ <li>Ваше приложение теперь может передавать аудиоданные как {@link java.nio.ByteBuffer}&nbsp;– в том же формате, что и {@link android.media.MediaCodec}.
+ <li>Опция {@link android.media.AudioTrack#WRITE_NON_BLOCKING WRITE_NON_BLOCKING} упрощает буферизацию и многопоточную обработку для некоторых изображений.
+</ul>
+
+<h3 id="MediaPlaybackControl">Управление воспроизведением мультимедиа</h3>
+<p>Используйте новые API для мультимедиа и уведомлений, чтобы в интерфейсе системы регистрировалось воспроизведение файлов, а также отображались обложки альбомов. Новые классы {@link android.media.session.MediaSession} и {@link android.media.session.MediaController} упрощают управление воспроизведением в интерфейсе и сервисах.</p>
+
+<p>Класс {@link android.media.session.MediaSession} теперь используется вместо {@link android.media.RemoteControlClient}. В нем представлен один набор методов обратного вызова для управления передачей и воспроизведением. Если ваше приложение поддерживает воспроизведение мультимедиа и работает на платформе Android <a href="{@docRoot}tv/index.html">TV</a> или <a href="{@docRoot}wear/index.html">Wear</a>, используйте класс {@link android.media.session.MediaSession} для управления передачей данных с помощью тех же методов обратного вызова.</p>
+
+<p>Новый класс {@link android.media.session.MediaController} позволяет создать собственное приложение для управления мультимедиа. Он обеспечивает безопасное отслеживание и управление воспроизведением видео через процесс пользовательского интерфейса приложения. При создании контроллера укажите объект {@link android.media.session.MediaSession.Token}, чтобы приложение могло взаимодействовать с указанным {@link android.media.session.MediaSession}. С помощью методов {@link android.media.session.MediaController.TransportControls} можно отправлять такие команды, как {@link android.media.session.MediaController.TransportControls#play() play()}, {@link android.media.session.MediaController.TransportControls#stop() stop()}, {@link android.media.session.MediaController.TransportControls#skipToNext() skipToNext()} и {@link android.media.session.MediaController.TransportControls#setRating(android.media.Rating) setRating()} для управления воспроизведением мультимедиа во время сеанса. Контроллер также позволяет зарегистрировать объект {@link android.media.session.MediaController.Callback} для отслеживания изменений метаданных и статусов во время сеанса.</p>
+
+<p>Кроме того, вы можете создавать уведомления с функцией управления воспроизведением. Связь с сессией обеспечивается посредством нового класса {@link android.app.Notification.MediaStyle}.</p>
+
+<h3 id="MediaBrowsing">Поиск и просмотр мультимедиа</h3>
+<p>В Android 5.0 приложения могут искать контент в библиотеке другого приложения с помощью нового API <a href="{@docRoot}reference/android/media/browse/package-summary.html">android.media.browse</a>. Чтобы открыть доступ к медиаконтенту в своем приложении, расширьте класс {@link android.service.media.MediaBrowserService}. При внедрении {@link android.service.media.MediaBrowserService} должен быть обеспечен доступ к {@link android.media.session.MediaSession.Token}, чтобы в приложении мог воспроизводиться медиаконтент, полученный через ваш сервис.</p>
+<p>Используйте класс {@link android.media.browse.MediaBrowser} для взаимодействия с сервисом браузера для мультимедиа. При создании экземпляра {@link android.media.browse.MediaBrowser} укажите название компонента для {@link android.media.session.MediaSession}. С помощью этого экземпляра браузера ваше приложение сможет подключиться к указанному сервису и получить объект {@link android.media.session.MediaSession.Token} для воспроизведения контента.</p>
+
+<h2 id="Storage">Хранение данных</h2>
+
+<h3 id="DirectorySelection">Выбор каталогов</h3>
+
+<p>В Android 5.0 расширена <a href="{@docRoot}guide/topics/providers/document-provider.html">инфраструктура обращения к памяти</a>, что позволяет пользователям выбирать целое поддерево каталога. Приложения получают доступ к чтению/записи во всех документах. Пользователю не приходится каждый раз подтверждать это.</p>
+
+<p>Чтобы выбрать поддерево каталога, создайте и отправьте цель {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE OPEN_DOCUMENT_TREE}. Система отображает все экземпляры {@link android.provider.DocumentsProvider}, которые поддерживают выбор поддерева. Пользователь может найти и выбрать нужный каталог. При этом возвращается URI для доступа к выбранному поддереву. Чтобы изучить его, используйте {@link android.provider.DocumentsContract#buildChildDocumentsUriUsingTree(android.net.Uri, java.lang.String) buildChildDocumentsUriUsingTree()}, {@link android.provider.DocumentsContract#buildDocumentUriUsingTree(android.net.Uri, java.lang.String) buildDocumentUriUsingTree()} и {@link android.content.ContentResolver#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String) query()}.</p>
+
+<p>Новый метод {@link android.provider.DocumentsContract#createDocument(android.content.ContentResolver, android.net.Uri, java.lang.String, java.lang.String) createDocument()} позволяет создавать новые документы и каталоги в поддереве. Для управления существующими документами используйте {@link android.provider.DocumentsContract#renameDocument(android.content.ContentResolver, android.net.Uri, java.lang.String) renameDocument()} и {@link android.provider.DocumentsProvider#deleteDocument(java.lang.String) deleteDocument()}. Проверьте {@link android.provider.DocumentsContract.Document#COLUMN_FLAGS COLUMN_FLAGS} и убедитесь, что провайдер поддерживает нужные вызовы.</p>
+
+<p>Если вы используете {@link android.provider.DocumentsProvider} и хотите, чтобы можно было выбрать поддерево, внедрите {@link android.provider.DocumentsProvider#isChildDocument(java.lang.String, java.lang.String) isChildDocument()} и добавьте {@link android.provider.DocumentsContract.Root#FLAG_SUPPORTS_IS_CHILD FLAG_SUPPORTS_IS_CHILD} в {@link android.provider.DocumentsContract.Root#COLUMN_FLAGS COLUMN_FLAGS}.</p>
+
+<p>В Android 5.0 также появились новые каталоги в едином хранилище. Они предназначены специально для пакетов. Медиафайлы оттуда включаются в {@link android.provider.MediaStore}. Новый элемент {@link android.content.Context#getExternalMediaDirs()} возвращает пути к каталогам на всех устройствах с единым хранилищем. Как и в случае {@link android.content.Context#getExternalFilesDir(java.lang.String) getExternalFilesDir()}, здесь не требуется дополнительных разрешений для перехода к возвращаемым файлам. Платформа периодически ищет новые файлы в указанных каталогах, но вы можете использовать для этого {@link android.media.MediaScannerConnection}.</p>
+
+<h2 id="Wireless">Беспроводные сети и подключения</h2>
+
+<h3 id="Multinetwork">Подключения к нескольким сетям</h3>
+<p>Android 5.0 поддерживает ряд API для работы в нескольких сетях одновременно. Приложение может постоянно искать доступные сети с определенными свойствами, а также подключаться к ним. Эта функция полезна, если ваше приложение работает в специальных сетях, таких как SUPL, MMS или сети с биллингом оператора связи, а также если для отправки данных используется определенный протокол.</p>
+
+<p>Чтобы приложение регулярно выполняло поиск доступных сетей и подключалось к ним, выполните следующие действия:</p>
+
+<ol>
+ <li>Создайте {@link android.net.ConnectivityManager}.</li>
+ <li>Используйте класс {@link android.net.NetworkRequest.Builder} для создания объекта {@link android.net.NetworkRequest}, укажите свойства сети и тип перехода, необходимый для приложения.</li>
+<li>Чтобы выполнить поиск подходящих сетей, вызовите {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} или {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()} и передайте объект {@link android.net.NetworkRequest}, а также внедрите {@link android.net.ConnectivityManager.NetworkCallback}. Если вы хотите сразу переключаться на подходящую сеть при ее обнаружении, используйте метод {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()}. Если же вам нужно только получать уведомления о найденных сетях, используйте {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()}.</li>
+</ol>
+
+<p>При обнаружении подходящей сети система подключается к ней и отправляет ответ {@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()}. Для получения дополнительных сведений о сети можно использовать объект {@link android.net.Network} в ответе. Он же применяется для перенаправления трафика в выбранную сеть.</p>
+
+<h3 id="BluetoothBroadcasting">Низкоэнергетический Bluetooth</h3>
+<p>В Android версии 4.3 была представлена поддержка <a href="{@docRoot}guide/topics/connectivity/bluetooth-le.html">низкоэнергетического Bluetooth</a> (<em>Bluetooth LE</em>) как основного способа передачи данных. Устройство на Android 5.0 может быть <em>периферийным</em> с поддержкой Bluetooth низкой мощности. Эта функция позволяет приложениям связываться с устройствами, расположенными неподалеку. Например, ваше приложение может работать как шагомер или отслеживать иные показатели, передавая данные на другое близко расположенное устройство по сети Bluetooth.</p>
+<p>Новый API {@link android.bluetooth.le} позволяет приложениям передавать рекламу, получать отчеты и устанавливать связь с другими устройствами, поддерживающими Bluetooth LE. Чтобы воспользоваться новыми функциями, добавьте в манифест разрешение {@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN}. Скачивая приложение или обновления для него в Google Play, пользователи должны дать разрешение на сбор данных о Bluetooth, управление этой функцией, а также на обмен информацией с устройствами по соседству.</p>
+
+<p>Чтобы начать передачу рекламы по Bluetooth LE на другие устройства, вызовите {@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()} и передайте данные о внедрении класса {@link android.bluetooth.le.AdvertiseCallback}. Объект обратного вызова получает отчет об успешном или неуспешном показе рекламы.</p>
+
+<p> С помощью класса {@link android.bluetooth.le.ScanFilter}, который появился в Android 5.0, ваше приложение сможет искать только определенные типы устройств. Чтобы начать поиск устройств с поддержкой Bluetooth LE, вызовите {@link android.bluetooth.le.BluetoothLeScanner#startScan(android.bluetooth.le.ScanCallback) startScan()} и передайте список фильтров. При вызове метода также следует внедрить {@link android.bluetooth.le.ScanCallback}, чтобы получать уведомления о найденной рекламе. </p>
+
+<h3 id="NFCEnhancements">Новые возможности NFC</h3>
+<p>В Android 5.0 реализованы следующие улучшения NFC:</p>
+
+<ul>
+<li>В меню <em>Поделиться</em> теперь доступен вариант Android Beam.</li>
+<li>Ваше приложение может активировать Android Beam на пользовательском устройстве путем вызова {@link android.nfc.NfcAdapter#invokeBeam(android.app.Activity) invokeBeam()}. Пользователю не нужно будет вручную подключаться к другому устройству с поддержкой NFC, чтобы передать данные.</li>
+<li>Новый метод {@link android.nfc.NdefRecord#createTextRecord(java.lang.String, java.lang.String) createTextRecord()} позволяет создать запись NDEF с текстовыми данными в кодировке UTF-8.</li>
+<li>В приложениях для платежей теперь можно динамически регистрировать идентификатор NFC (AID), просто вызывая <code><a href="{@docRoot}reference/android/nfc/cardemulation/CardEmulation.html#registerAidsForService(android.content.ComponentName, java.lang.String, java.util.List<java.lang.String>)">registerAidsForService()</a></code>. Вы также можете использовать {@link android.nfc.cardemulation.CardEmulation#setPreferredService(android.app.Activity, android.content.ComponentName) setPreferredService()}, чтобы указать предпочтительный сервис эмуляции карт, который будет использоваться при определенных действиях в фоне.</li>
+</ul>
+
+<h2 id="Power">Project Volta</h2>
+
+<p>Помимо новых функций Android 5.0 также отличается улучшенными возможностями для экономии заряда аккумулятора. С помощью новых API и инструментов можно оптимизировать расход энергии для приложения.</p>
+
+<h3 id="JobScheduler">Планирование заданий</h3>
+<p>В Android 5.0 есть API {@link android.app.job.JobScheduler}. Эта новинка позволяет оптимизировать расход энергии за счет асинхронного распределения заданий, которые выполняются не сразу или только в определенных условиях (например, при зарядке устройства). Планирование заданий полезно в следующих случаях:</p>
+<ul>
+ <li>В приложении есть недоступные пользователю процессы, которые можно отложить.</li>
+ <li>В приложении есть процессы, которые лучше выполнять во время зарядки.</li>
+ <li>В приложении есть задачи, которые требуют подключения к сети или Wi-Fi.</li>
+ <li>В приложении есть ряд задач, которые нужно выполнять одновременно и регулярно.</li>
+
+</ul>
+
+<p>Каждая элементарная операция заключена в объект {@link android.app.job.JobInfo}, который определяет критерии для расписания.</p>
+
+<p>Чтобы настроить процесс выполнения задачи, используйте класс {@link android.app.job.JobInfo.Builder}. Вы можете указать определенные условия, например:</p>
+
+<ul>
+ <li>Запуск при зарядке устройства.</li>
+ <li>Запуск при подключении устройства к неограниченной сети.</li>
+ <li>Запуск в режиме ожидания.</li>
+ <li>Завершение в указанный срок или максимально быстрое выполнение.</li>
+</ul>
+
+<p>Например, для выполнения задачи в неограниченной сети можно добавить следующий код:</p>
+
+<pre>
+JobInfo uploadTask = new JobInfo.Builder(mJobId,
+ mServiceComponent /* JobService component */)
+ .setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED)
+ .build();
+JobScheduler jobScheduler =
+ (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
+jobScheduler.schedule(uploadTask);
+</pre>
+
+<p>Если питание устройства стабильно (то есть оно подключено к сети более 2 минут, а аккумулятор <a href="{@docRoot}reference/android/content/Intent.html#ACTION_BATTERY_OKAY">достаточно заряжен</a>), система будет выполнять все запланированные задания, даже если указанное время еще не наступило.</p>
+
+<p>Пример использования API {@link android.app.job.JobScheduler} см. в образце {@code JobSchedulerSample} данного выпуска.</p>
+
+<h3 id="PowerMeasurementTools">Инструменты для разработчиков (использование батареи)</h3>
+
+<p>Новая команда {@code dumpsys batterystats} позволяет получить интересные статистические данные об использовании аккумуляторов в устройствах (с учетом уникальных идентификаторов пользователей&nbsp;– UID). Статистика включает в себя следующие данные:</p>
+
+<ul>
+<li>Историю событий, связанных с работой аккумулятора.
+<li>Общую статистику по работе устройства.
+<li>Примерные энергозатраты по отдельным идентификаторам пользователей и компонентам системы.
+<li>Расход на передачу мобильных данных для каждого приложения (мс на пакет).
+<li>Общую статистику системы для каждого идентификатора пользователя.
+<li>Общую статистику приложения для каждого идентификатора пользователя.
+</ul>
+
+<p>Чтобы узнать о разных функциях для вывода конкретных данных, используйте опцию {@code --help}. Например, чтобы получить статистику по энергозатратам для определенного приложения с момента последней зарядки устройства, выполните эту команду:
+<pre>
+$ adb shell dumpsys batterystats --charged &lt;package-name&gt;
+</pre>
+
+<p>Вы можете воспользоваться инструментом <a href="https://github.com/google/battery-historian" class="external-link">Battery Historian</a> при выводе команды {@code dumpsys}, чтобы создать HTML-визуализацию событий, связанных с расходом энергии и сохраненных в журналах. Это позволит вам обнаружить проблемы, приводящие к низкой энергоэффективности приложения.</p>
+
+<h2 id="Enterprise">Android для работы и учебы</h2>
+<h3 id="ManagedProvisioning">Контролируемые профили</h3>
+
+<p>В Android 5.0 представлены новые функции для использования приложений в корпоративной среде. <a href="{@docRoot}guide/topics/admin/device-admin.html">Администратор устройства</a> может создать отдельный <em>контролируемый профиль</em> для пользователя, у которого есть личный аккаунт. Приложения, связанные с такими профилями, отображаются наряду с прочими в списках недавно использованных, в уведомлениях и на экране запуска.</p>
+
+<p>Чтобы запустить процесс настройки контролируемых профилей, отправьте {@link android.app.admin.DevicePolicyManager#ACTION_PROVISION_MANAGED_PROFILE ACTION_PROVISION_MANAGED_PROFILE} в {@link android.content.Intent}. При успешном вызове система вернет ответ {@link android.app.admin.DeviceAdminReceiver#onProfileProvisioningComplete(android.content.Context, android.content.Intent) onProfileProvisioningComplete()}. Затем вы сможете вызвать {@link android.app.admin.DevicePolicyManager#setProfileEnabled(android.content.ComponentName) setProfileEnabled()} и включить нужный профиль.</p>
+
+<p>По умолчанию в контролируемых профилях используется лишь небольшое число приложений. Чтобы установить дополнительные приложения, вызовите {@link android.app.admin.DevicePolicyManager#enableSystemApp(android.content.ComponentName, android.content.Intent) enableSystemApp()}.</p>
+
+<p>В модулях запуска можно использовать новый класс {@link android.content.pm.LauncherApps}, чтобы получить список возможных действий для текущего пользователя и для всех связанных с ним контролируемых профилей. Контролируемые приложения могут быть отмечены дополнительным значком. Чтобы добавить значок, вызовите {@link android.content.pm.PackageManager#getUserBadgedIcon(android.graphics.drawable.Drawable, android.os.UserHandle) getUserBadgedIcon()}.</p>
+
+<p>Подробнее об использовании новых функций см. в примере внедрения {@code BasicManagedProfile} в данном выпуске.</p>
+
+<h3 id="DeviceOwner">Владелец устройства</h3>
+<p>В Android 5.0 можно использовать приложение, которое назначает владельца устройства. <em>Владелец устройства</em>&nbsp;– это <a href="{@docRoot}guide/topics/admin/device-admin.html">администратор устройства</a>, который может создавать и удалять вторичных пользователей, а также менять глобальные настройки. Он использует методы из класса {@link android.app.admin.DevicePolicyManager} для точного управления конфигурацией, безопасностью и приложениями на доступных устройствах. У устройства может быть только один действующий владелец в определенный момент времени.</p>
+
+<p>Чтобы использовать эту функцию, необходимо с помощью NFC перенести данные из программируемого приложения на устройство, которое ещё не сконфигурировано. При этом передаются те же данные, что и в процессе, который описан в разделе <a href="#ManagedProvisioning">Контролируемые профили</a>.</p>
+
+<h3 id="ScreenPinning">Блокировка в приложении</h3>
+
+<p>В Android 5.0 используется новый API для блокировки в приложении. С его помощью можно временно запретить пользователям отменять задачи или получать уведомления. Это может быть полезно, например, если вы разрабатываете образовательные приложения, требующие высокой степени контроля, а также однозадачные или киоск-приложения. При такой блокировке пользователи не смогут просматривать уведомления, открывать другие приложения или переходить на главный экран, пока этот режим не будет отключен.</p>
+
+<p>Режим блокировки в приложении можно активировать двумя способами:</p>
+
+<ul>
+<li><strong>Вручную.</strong> В разделе <em>Настройки &gt; Безопасность &gt; Блокировка в приложении</em> пользователи могут выбрать задачи, которые требуется закрепить. Нужно просто нажать на зеленый значок.</li> <li><strong>Программно.</strong> Вызовите в приложении {@link android.app.Activity#startLockTask() startLockTask()}, чтобы активировать блокировку. Если запрашивающее приложение не является владельцем устройства, пользователь должен будет подтвердить действие. Владелец устройства может вызвать метод {@link android.app.admin.DevicePolicyManager#setLockTaskPackages(android.content.ComponentName, java.lang.String[]) setLockTaskPackages()}, чтобы разрешить приложениям активировать этот режим без согласия пользователя.</li>
+</ul>
+
+<p>Если блокировка задач активна, происходит следующее:</p>
+
+<ul>
+<li>Строка состояния пуста, уведомления и сведения о состоянии скрыты.</li>
+<li>Кнопки для перехода на главную страницу и к списку недавно использованных приложений скрыты.</li>
+<li>Новые действия в других приложениях недоступны.</li>
+<li>В действующем приложении действия выполняться могут, если при этом не создаются новые задачи.</li>
+<li>Если блокировка в приложении активирована владельцем устройства, пользователь не может выйти из приложения, пока последний не вызовет {@link android.app.Activity#stopLockTask() stopLockTask()}.</li>
+<li>Если блокировка активирована другим приложением или самим пользователем, переключиться в другой режим можно, нажав кнопки "Назад" и "Недавние".</li>
+
+</ul>
+
+<h2 id="Printing">Инфраструктура печати</h2>
+
+<h3 id="PDFRender">Обработка PDF как растрового изображения</h3>
+<p>Теперь PDF-документы можно превращать в растровые изображения для печати. Для этого создан новый класс {@link android.graphics.pdf.PdfRenderer}. Необходимо указать атрибут {@link android.os.ParcelFileDescriptor} с возможностью поиска (чтобы обеспечить удобный доступ к контенту). Система добавит туда содержимое для печати. Приложение получает страницу с помощью {@link android.graphics.pdf.PdfRenderer#openPage(int) openPage()}, а затем вызывает {@link android.graphics.pdf.PdfRenderer.Page#render(android.graphics.Bitmap, android.graphics.Rect, android.graphics.Matrix, int) render()}, чтобы преобразовать {@link android.graphics.pdf.PdfRenderer.Page} в растровый формат. Вы также можете настроить дополнительные параметры, если в графический файл необходимо превратить только часть документа (например, для <a href="http://en.wikipedia.org/wiki/Tiled_rendering" class="external-link">мозаичной обработки</a> и увеличения фрагментов).</p>
+
+<p>Подробнее об использовании нового API см. в примере {@code PdfRendererBasic}.</p>
+
+<h2 id="System">Система</h2>
+<h3 id="AppUsageStatistics">Статистика по использованию приложений</h3>
+<p>Новый API {@link android.app.usage} позволяет просматривать историю использования приложений на устройствах Android. При этом вы получаете более подробные данные, чем в случае с устаревшим методом {@link android.app.ActivityManager#getRecentTasks(int, int) getRecentTasks()}. Чтобы использовать новый API, необходимо добавить разрешение {@code "android.permission.PACKAGE_USAGE_STATS"} в манифест. Пользователь также должен разрешить доступ к этому приложению в разделе <em>Настройки &gt; Безопасность &gt; Приложения</em>.</p>
+
+<p>Система собирает данные об использовании отдельных приложений за день, неделю, месяц и год. Максимальные сроки хранения данных в системе:</p>
+
+<ul>
+ <li>Ежедневные: 7&nbsp;дней.</li>
+ <li>Еженедельные: 1&nbsp;месяц.</li>
+ <li>Ежемесячные: 6&nbsp;месяцев.</li>
+ <li>Ежегодные: 2&nbsp;года.</li>
+</ul>
+
+<p>Для каждого приложения в системе сохраняются следующие данные:</p>
+<ul>
+<li>Дата последнего использования приложения.</li>
+<li>Общее время активной работы приложения за указанный срок (день, неделю, месяц или год).</li>
+<li>Временная метка, указывающая на то, когда компонент (определяемый по названию пакета или действия) был перемещен в фон или в основные процессы.</li>
+<li>Временная метка, указывающая на изменение конфигурации устройства (например, на поворот изображения на экране).</li>
+</ul>
+
+<h2 id="TestingA11y">Тестирование и доступность </h2>
+
+<h3 id="TestingA11yImprovements">Новые возможности тестирования и оценки доступности</h3>
+<p>В Android 5.0 реализованы следующие функции для тестирования и оценки доступности:</p>
+
+<ul>
+<li>Новые методы {@link android.app.UiAutomation#getWindowAnimationFrameStats() getWindowAnimationFrameStats()} и {@link android.app.UiAutomation#getWindowContentFrameStats(int) getWindowContentFrameStats()} собирают статистику по кадрам для анимации в окнах и для контента. С их помощью можно создавать диагностические тесты и оценивать, с достаточной ли частотой приложение показывает кадры. Так вы сможете следить за удобством для пользователей.</li>
+
+<li>Новый метод {@link android.app.UiAutomation#executeShellCommand(java.lang.String) executeShellCommand()} позволяет выполнять команды для оболочки непосредственно в диагностических тестах. Выполнение команды похоже на запуск {@code adb shell} с хоста, подключенного к устройству. Это позволяет использовать инструменты на основе оболочки, такие как {@code dumpsys}, {@code am}, {@code content} и {@code pm}.</li>
+
+<li>Сервисы и инструменты для тестирования, которые используют API специальных возможностей (например, <a href="{@docRoot}tools/help/uiautomator/index.html">{@code UiAutomator}</a>), теперь могут получать подробные сведения о свойствах окон на экране, с которыми взаимодействуют пользователи. Чтобы получить список объектов {@link android.view.accessibility.AccessibilityWindowInfo}, вызовите новый метод {@link android.accessibilityservice.AccessibilityService#getWindows() getWindows()}.</li>
+
+<li>Новый класс {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} позволяет определить стандарт для пользовательских действий, выполняемых на {@link android.view.accessibility.AccessibilityNodeInfo}. Класс {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} заменяет API, связанные с действиями, которые ранее использовались в {@link android.view.accessibility.AccessibilityNodeInfo}.</li>
+
+<li>Android 5.0 обеспечивает более точное управление синтезом речи и распознаванием текста в приложении. Класс {@link android.speech.tts.Voice} позволяет использовать в приложении голосовые профили, связанные с определенными локалями, качеством и временем реакции, а также задавать параметры для определенных систем.</li>
+</ul>
+
+<h2 id="IME">Редактор способов ввода (IME)</h2>
+
+<h3 id="Switching">Упрощенное переключение между языками ввода</h3>
+
+<p>В Android 5.0 пользователям будет проще переключаться между <a href="{@docRoot}guide/topics/text/creating-input-method.html">редакторами способов ввода</a>, которые поддерживаются платформой. С помощью одного действия (обычно это нажатие на значок глобуса на электронной клавиатуре) можно будет переключаться между всеми доступными языками. Это обеспечивается посредством метода {@link android.view.inputmethod.InputMethodManager#shouldOfferSwitchingToNextInputMethod(android.os.IBinder) shouldOfferSwitchingToNextInputMethod()}.</p>
+
+<p>Кроме того, теперь инфраструктура проверяет, есть ли в следующем редакторе механизм переключения (то есть поддерживается ли такая функция). Для замены всегда выбирается редактор способов ввода с механизмом переключения. Это обеспечивается посредством метода {@link android.view.inputmethod.InputMethodManager#switchToNextInputMethod(android.os.IBinder, boolean) switchToNextInputMethod()}.
+
+<p>Пример использования обновленного API для переключения способов ввода см. в образце внедрения клавиатуры в данном выпуске. Подробнее о том, как обеспечить переключение между способами, читайте в разделе <a href="{@docRoot}guide/topics/text/creating-input-method.html">Создание способов ввода</a>.
+</p>
+
+<h2 id="Manifest">Объявление манифеста</h2>
+
+<h3 id="ManifestFeatures">Объявляемые обязательные функции</h3>
+<p>В элементе <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> теперь могут содержаться приведенные ниже значения, а ваше приложение будет устанавливаться только на устройства, обладающие нужными функциями.</p>
+
+<ul>
+<li>{@link android.content.pm.PackageManager#FEATURE_AUDIO_OUTPUT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_POST_PROCESSING}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_SENSOR}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_RAW}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_LEVEL_FULL}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_GAMEPAD}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LIVE_TV}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_MANAGED_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LEANBACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_OPENGLES_EXTENSION_PACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SECURELY_REMOVES_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_AMBIENT_TEMPERATURE}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_HEART_RATE_ECG}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_RELATIVE_HUMIDITY}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_VERIFIED_BOOT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_WEBVIEW}</li>
+</ul>
+
+<h3 id="Permissions">Разрешения для пользователей</h3>
+
+<p>В элементе <a href="{@docRoot}guide/topics/manifest/uses-permission-element.html">{@code <uses-permission>}</a> теперь поддерживается приведенное ниже разрешение, с помощью которого вы сможете обеспечить доступ приложения к определенным API.</p>
+
+<ul>
+<li>{@link android.Manifest.permission#BIND_DREAM_SERVICE}: при работе с API уровня 21 и выше это разрешение требуется для сервиса <a href="{@docRoot}about/versions/android-4.2.html#Daydream">Daydream</a>, чтобы к нему могла подключаться только система.</li>
+</ul>
diff --git a/docs/html-intl/intl/ru/about/versions/lollipop.jd b/docs/html-intl/intl/ru/about/versions/lollipop.jd
new file mode 100644
index 0000000..2f814be
--- /dev/null
+++ b/docs/html-intl/intl/ru/about/versions/lollipop.jd
@@ -0,0 +1,251 @@
+page.title=Android Lollipop
+
+@jd:body
+
+
+
+
+
+
+
+ <div style="padding:0px 0px 0px 20px;float:right;margin:0 -10px 0 0">
+ <img src="{@docRoot}images/home/l-hero_2x.png" srcset="{@docRoot}images/home/l-hero.png 1x, {@docRoot}images/home/l-hero_2x.png 2x" width="460" height="300" >
+ </div>
+
+ <div class="landing-docs" style="float:right;clear:both;margin:68px 0 2em 3em;">
+ <div class="col-4 normal-links highlights" style="font-size:12px;">
+ <h3 id="thisd" >Ключевые функции для разработчиков</h3>
+ <ul style="list-style-type:none;">
+ <li><a href="#Material">Material Design</a></li>
+ <li><a href="#Perf">Оптимизация и эффективность</a></li>
+ <li><a href="#Notifications">Уведомления</a></li>
+ <li><a href="#TV">Приложения на большом экране</a></li>
+ <li><a href="#Documents">Приложения для работы с документами</a></li>
+ <li><a href="#Connectivity">Расширенные функции подключения</a></li>
+ <li><a href="#Graphics">Графика в высоком разрешении</a></li>
+ <li><a href="#Audio">Новые возможности аудио</a></li>
+ <li><a href="#Camera">Дополнительные функции камеры и видео</a></li>
+ <li><a href="#Work">Android для работы</a></li>
+ <li><a href="#ScreenCapture">Сохранение и отправка данных с экрана</a></li>
+ <li><a href="#Sensors">Новые типы сенсоров</a></li>
+ <li><a href="#WebView">Chromium WebView</a></li>
+ <li><a href="#Accessibility">Специальные возможности и способы ввода</a></li>
+ <li><a href="#Battery">Инструменты для создания приложений с экономией энергии</a></li>
+ </ul>
+ </div>
+</div>
+
+
+
+
+
+
+
+<p>Представляем вам Android 5.0 Lollipop&nbsp;– самую новую и продвинутую версию операционной системы Android!</p>
+
+<p>В этой версии реализовано множество новых функций для пользователей и тысячи API для разработчиков. Android теперь используется не только для телефонов, планшетов и носимых устройств, но также для телевизоров и автомобилей.</p>
+
+<p>Подробнее о новых API для разработчиков см. в соответствующем <a href="{@docRoot}about/versions/android-5.0.html">обзоре</a>. Если же вас интересует информация об Android 5.0 для пользователей, посетите сайт <a href="http://www.android.com/versions/lollipop-5-0/">www.android.com</a>.</p>
+
+<h2 id="Material">Material Design</h2>
+
+<p>В Android 5.0 реализована концепция <a href="http://www.google.com/design/spec">Material Design</a>. Расширенный набор инструментов в интерфейсе позволяет c легкостью использовать новые возможности в приложениях. </p>
+
+
+
+<p>Новый <strong>3D-режим</strong> позволяет добавить глубину (ось z), чтобы приподнять объекты над плоскостью и создать <strong>реалистичные тени</strong> даже при движении.</p>
+
+
+<p>Встроенные <strong>переходы действий</strong> обеспечивают непрерывное движение, как в анимации. Тема Material добавляет в действия переходы, в том числе возможность использовать <strong>общие визуальные элементы</strong> в разных действиях.</p>
+
+
+
+<div style="width:290px;margin-right:35px;float:left">
+ <div class="framed-nexus5-port-span-5">
+ <video class="play-on-hover" autoplay="">
+ <source src="/design/material/videos/ContactsAnim.mp4">
+ <source src="/design/videos/ContactsAnim.webm">
+ <source src="/design/videos/ContactsAnim.ogv">
+ </video>
+ </div>
+ <div style="font-size:10pt;margin-left:20px;margin-bottom:30px">
+ <em>Чтобы повторить воспроизведение видео, нажмите на экран устройства</em>
+ </div>
+</div>
+
+
+<p>Для кнопок, флажков и других элементов управления в приложении можно создать пульсирующую анимацию.
+
+<p>Вы также можете определять векторные области рисования в XML и по-разному их анимировать. Векторные области масштабируются без потери разрешения, поэтому они идеально подходят для одноцветных значков в приложениях.</p>
+
+<p>Новый системный поток обработки <strong>RenderThread</strong> обеспечивает плавность анимации даже при задержках в основном потоке интерфейса. </p>
+
+
+<h2 id="Perf">Оптимизация и эффективность</h2>
+
+<p>Android 5.0 отличается более быстрыми и эффективными вычислениями с плавным интерфейсом.</p>
+
+<p>Android теперь работает исключительно на базе новой среды выполнения <strong>ART</strong>, созданной специально для поддержки предварительной компиляции (AOT), динамической компиляции (JIT) и интерпретируемого кода. Эта среда поддерживается архитектурами ARM, x86 и MIPS. Кроме того, она полностью совместима с 64-разрядными системами.</p>
+
+<p>ART улучшает эффективность приложений и повышает скорость их работы. Оптимизированная очистка памяти сокращает количество и продолжительность пауз между событиями, так что приложение не пропускает кадры. Кроме того, ART динамически корректирует использование памяти, чтобы основные процессы протекали более эффективно. </p>
+
+<p>Android 5.0 поддерживает <strong>64-разрядные архитектуры</strong>, которые используются в NVIDIA Tegra K1 для Nexus 9. Оптимизация расширяет пространство адресов и повышает эффективность определенных вычислений. Приложения, написанные на языке Java, автоматически действуют как 64-разрядные. Никаких модификаций не требуется. Если в приложении используется собственный код, NDK будет поддерживать новые ABI для ARM v8, x86-64 и MIPS-64.</p>
+
+<p>В Android 5.0 также улучшена синхронизация аудио и видео. Каналы аудио и видео передают более точные временные метки. Благодаря этому улучшается качество работы игровых и видеоприложений.</p>
+
+
+<h2 id="Notifications">Уведомления</h2>
+
+<p>Уведомления в Android 5.0 стали более заметными и интерактивными, с возможностью настройки. </p>
+
+<img src="{@docRoot}images/versions/notification-headsup.png" style="float:right; margin:0 0 40px 60px" width="300" height="224" />
+
+<p>При желании пользователя <strong>на экране блокировки</strong> могут отображаться только определенные данные из уведомлений. Также можно и отключить их насовсем, чтобы обеспечить безопасность личных данных. </p>
+
+<p>Важные сообщения (например, о входящих звонках) отображаются во <strong>всплывающих уведомлениях</strong>. Это небольшие окна, где пользователь может выполнять действия, не выходя из открытого приложения.</p>
+
+<p>Теперь в уведомления можно добавить <strong>новые метаданные</strong>, чтобы собирать информацию о контактах (для рейтинга), категориях и приоритете.</p>
+
+<p>В новом шаблоне уведомления используются единые средства управления мультимедиа: до 6&nbsp;кнопок действий, в том числе пользовательские (например, "палец вверх"). Теперь можно обойтись без RemoteViews!</p>
+
+
+
+<h2 id="TV">Ваши приложения на большом экране</h2>
+
+<p><a href="http://developer.android.com/tv/index.html">Android TV</a>&nbsp;– это полнофункциональная телеплатформа для использования приложений на больших экранах. Она позволяет с легкостью находить контент благодаря персональным рекомендациям и голосовому поиску, а затем просматривать его на телеэкране.</p>
+
+<p>С Android TV вы можете создавать <strong>впечатляющие материалы</strong> для игры или приложения. Также эта платформа поддерживает подключение к игровым контроллерам и другим устройствам ввода. Воспользуйтесь <strong>эффективной инфраструктурой</strong> в <a href="{@docRoot}tools/support-library/features.html#v17-leanback">библиотеке поддержки версии 17</a>, чтобы создать интерфейс для телеэкранов с диагональю до 3 метров.</p>
+
+<p>Инфраструктура <strong>Android TV Input Framework</strong> (TIF) обеспечивает поддержку видеопотоков из таких источников, как HDMI, ТВ-тюнеры и приемники IP-телевидения. Также поддерживается поиск непосредственно на экране и рекомендации по метаданным, полученным TV Input. Для управления несколькими устройствами с помощью единого пульта имеется сервис HDMI-CEC. </p>
+
+<p>Инфраструктура TV Input Framework поддерживает различные устройства ввода. В ней есть единый интерфейс для поиска и просмотра интересного контента. Используйте эти возможности, чтобы ваш контент стал более доступным для просмотра на телеэкране.</p>
+
+
+
+<img src="{@docRoot}images/versions/recents_screen_2x.png" srcset="{@docRoot}images/versions/recents_screen.png 1x, {@docRoot}images/versions/recents_screen_2x.png 2x" style="float:right; margin:0 0 40px 60px" width="300" height="521" />
+
+<h2 id="Documents">Приложения для работы с документами</h2>
+
+<p>В Android 5.0 изменился режим просмотра программ, который раньше назывался "Недавние приложения". Теперь выполнять несколько задач одновременно стало проще.</p>
+
+<p>Новые API позволяют отображать различные действия в приложении как отдельные документы наряду с прочими недавними процессами.</p>
+
+<p>Благодаря этому пользователи могут быстро переходить к вашему контенту или сервисам. Например, можно отдельно отображать файлы, матчи в игре или чаты в социальном приложении. </p>
+
+
+
+<h2 id="Connectivity">Расширенные функции подключения</h2>
+
+<p>В Android 5.0 добавлены новые API для поддержки одновременных операций в приложениях с использованием <strong>низкоэнергетического Bluetooth</strong> (BLE). Работает как сканирование (основной режим), так и реклама (дополнительный режим).</p>
+
+<p>Новые функции для <strong>многосетевой</strong> работы позволяют приложениям узнавать о свойствах доступных сетей (Wi-Fi, сотовых, с отслеживанием трафика и т.&nbsp;п.). Затем приложение может запросить установку соединения и отреагировать на обрыв связи или другие изменения в сети.</p>
+
+<p>API <strong>NFC</strong> позволяет приложениям динамически регистрировать соответствующий идентификатор (AID). Также можно указать предпочитаемый сервис эмуляции карт и создать запись NDEF с текстовыми данными в кодировке UTF-8.</p>
+
+
+
+<h2 id="Graphics">Графика в высоком разрешении</h2>
+
+<p>Поддержка <strong><a href="http://www.khronos.org/opengles/3_X/">Khronos OpenGL ES 3.1</a></strong> обеспечивает максимальное качество 2D и 3D-графики в играх и других приложениях. </p>
+
+<p>OpenGL ES 3.1 поддерживает шейдеры, трафаретные шаблоны, усовершенствованные визуальные эффекты, высококачественное сжатие текстур ETC2/EAC и их обработку, стандартизацию размера текстур и формата буферизации при обработке, а также другие функции.</p>
+
+
+<div class="figure" style="width:350px; margin:0 0 0 60px">
+<img src="{@docRoot}images/versions/rivalknights.png" style="float:right;" width="350" height="525" />
+<p class="img-caption">В игре Rival Knights от Gameloft используется технология ASTC (адаптивное масштабируемое сжатие текстур) из AEP и вычислительные шейдеры из ES 3.1. Это позволяет добавлять эффекты в расширенном динамическом диапазоне (HDR) и детализировать графику.</p>
+</div>
+
+<p>В Android 5.0 также используется <strong>AEP</strong>&nbsp;– набор расширений OpenGL ES, который обеспечивает доступ к таким функциям как мозаичные и геометрические шейдеры, сжатие текстур ASTC, посэмпловая интерполяция, затенение и&nbsp;т.&nbsp;п. C AEP вы сможете создать высококачественную графику для разных процессоров.</p>
+
+
+<h2 id="Audio">Новые возможности аудио</h2>
+
+<p>Новая функция аудиозахвата обеспечивает <strong>ввод звука с малой задержкой</strong>. При этом используется новый поток захвата, который блокируется только при чтении, быстрые клиенты с поддержкой собственной частоты, подсчет каналов и битовой глубины, а также нормальные клиенты с повторной выборкой, сменой статуса каналов (выше/ниже) и битовой глубины.</p>
+
+<p>Многоканальное <strong>смешивание аудиопотоков</strong> позволяет профессиональным аудиоприложениям использовать до 8 каналов (в том числе 5.1 и 7.1).</p>
+
+<p>Приложения могут открывать доступ к контенту и <strong>получать контент</strong> из других источников, а затем воспроизводить его. Контент передается при помощи интерфейса с поддержкой запросов. Он не обязательно должен физически располагаться на устройстве.</p>
+
+<p>Для <strong>преобразования текста в речь</strong> в приложениях используются голосовые профили, связанные с конкретными локалями, качеством и временем реакции. В новых API также есть функции проверки ошибок при синтезе речи, синтез сетей, распознавание языка и поддержка резервных сетей.</p>
+
+<p>Android теперь поддерживает подключение стандартных периферийных устройств через <strong>USB</strong>. Пользователи могут подключать наушники, динамики, микрофоны и&nbsp;т.&nbsp;п. Android 5.0 также поддерживает аудиокодеки <strong>Opus</strong>.</p>
+
+<p>Новые API <strong>{@link android.media.session.MediaSession}</strong> упрощают управление воспроизведением мультимедиа на разных устройствах.</p>
+
+
+<h2 id="Camera">Дополнительные функции камеры и видео</h2>
+
+<p>В Android 5.0 присутствуют <strong>совершенно новые API для камеры</strong>. Поддерживается съемка в форматах YUV и Bayer RAW, а также управление выдержкой, чувствительностью ISO и длительностью кадра (покадрово). Новый поток видео с полной синхронизацией позволяет делать снимки в формате YUV без сжатия и в полном разрешении, на скорости 30&nbsp;к/с (на поддерживаемых устройствах).</p>
+
+<p>Помимо изображений можно сохранять и метаданные, например модели шумов и оптическую информацию с камеры.</p>
+
+<p>Приложения для передачи видео по сети теперь могут применять <strong>высокоэффективное кодирование видео (HEVC)</strong> H.265. </p>
+
+<p>В Android 5.0 также добавлена поддержка <strong>туннелирования мультимедиа</strong>. Это позволяет обрабатывать контент в сверхвысоком разрешении (4K) и одновременно воспроизводить сжатые аудио- и видеоматериалы. </p>
+
+
+
+<div class="figure" style="width:320px; margin:1em 0 0 20px;padding-left:2em;">
+<img style="float:right; margin:0 1em 1em 2em" src="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png" srcset="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png 2x" alt="" width="300" />
+<p class="img-caption">Личные и рабочие приложения отображаются в едином формате и имеют значки для быстрой идентификации.</p>
+</div>
+
+
+<h2 id="Work">Android для работы</h2>
+
+<p>Новый <a href="{@docRoot}about/versions/android-5.0.html#Enterprise">процесс создания контролируемых профилей</a> позволяет добавлять защищенные рабочие профили на личном устройстве. Приложения, данные в которых используются рабочим профилем и доступны ИТ-администратору, отмечены на панели запуска соответствующим значком.</p>
+
+<p>Уведомления для личного и рабочего профилей отображаются в едином формате. Данные для каждого профиля хранятся отдельно, даже если одно и то же приложение используется владельцами разных профилей.</p>
+
+<p>Для корпоративных устройств ИТ-администраторы могут сразу настроить приложение, определяющее <a href="{@docRoot}about/versions/android-5.0.html#DeviceOwner">владельца</a>. С его помощью можно установить общие настройки, а затем предоставлять доступ к устройству определенным сотрудникам.</p>
+
+
+
+<h2 id="ScreenCapture">Сохранение и отправка данных с экрана</h2>
+
+<p>Android 5.0 поддерживает функцию сохранения данных с экрана и отправки их пользователям через приложения. </p>
+
+<p>При наличии пользовательского разрешения приложения могут сохранять данные с экрана в формате видео и транслировать его по сети.</p>
+
+
+<h2 id="Sensors">Новые типы сенсоров</h2>
+
+<p>В Android 5.0 используется новый <strong>сенсор наклона</strong>. Это упрощает распознавание действий на устройствах, а также <strong>отслеживание сердцебиения</strong> человека, который касается устройства. </p>
+
+<p>Для распознавания специальных действий, таких как жесты <em>активации</em>, <em>выбора</em> и <em>быстрого просмотра</em>, теперь используются новые <strong>составные сенсоры</strong>.</p>
+
+
+
+<h2 id="WebView">Chromium WebView</h2>
+
+<div style="float:right;margin:1em 2em 1em 2em;">
+ <img src="/images/kk-chromium-icon.png" alt="" height="160" style="margin-bottom:0em;">
+</div>
+
+<p>Первоначальный выпуск для Android 5.0 включает версию Chromium для {@link android.webkit.WebView}, созданную на основе Chromium M37, но с поддержкой <strong>WebRTC</strong>, <strong>WebAudio</strong> и <strong>WebGL</strong>. </p>
+
+<p>Chromium M37 также обеспечивает поддержку всех спецификаций <strong>веб-компонентов</strong>: Custom Elements, Shadow DOM, HTML Imports и Templates. То есть вы можете использовать <a href="http://polymer-project.org/">Polymer</a> и соответствующие <a href="https://www.polymer-project.org/docs/elements/material.html">элементы Material Design</a> в WebView без полизаполнения.</p>
+
+<p>Хотя WebView создается на базе Chromium начиная с Android версии 4.4, в Google Play теперь можно скачать обновление для Chromium.</p>
+
+<p>Доступны все новые версии. Рекомендуется выполнить обновление, чтобы получить все усовершенствования и исправления для WebView, а также самые новые API для поддержки Android 5.0 и выше.</p>
+
+
+
+<h2 id="Accessibility">Специальные возможности и способы ввода</h2>
+
+<p>Новые API специальных возможностей позволяют получать подробные сведения об окнах на экране, с которыми могут взаимодействовать пользователи. Также можно задать стандарты или определенные действия для элементов интерфейса.</p>
+
+<p>Новые API для редакторов способов ввода обеспечивают быстрое переключение между доступными способами.</p>
+
+
+
+<h2 id="Battery">Инструменты для создания приложений с экономией энергии</h2>
+
+<p>Новые API для <strong>планирования заданий</strong> позволяют экономить энергию аккумулятора, откладывая определенные действия до времени зарядки или подключения к сети Wi-Fi.</p>
+
+<p>Новая команда <code>dumpsys batterystats</code> создает <strong>статистику использования аккумулятора</strong>, чтобы вы могли проанализировать расход энергии и узнать, как на него влияет ваше приложение. Вы можете просмотреть историю использования аккумулятора, примерный расход энергии на каждого пользователя (по идентификатору) и компонент системы, а также другие данные.</p>
+
+<img src="{@docRoot}images/versions/battery_historian.png" srcset="{@docRoot}images/versions/battery_historian@2x.png 2x" alt="" width="760" height="462" />
+<p class="img-caption">Инструмент Battery Historian позволяет визуализировать статистику из <code>dumpsys batterystats</code>, чтобы было проще устранять неполадки. Подробнее читайте на странице <a href="https://github.com/google/battery-historian">https://github.com/google/battery-historian</a>.</p>
diff --git a/docs/html-intl/intl/zh-cn/about/versions/android-5.0.jd b/docs/html-intl/intl/zh-cn/about/versions/android-5.0.jd
index 9c3dd5c..8e20975 100644
--- a/docs/html-intl/intl/zh-cn/about/versions/android-5.0.jd
+++ b/docs/html-intl/intl/zh-cn/about/versions/android-5.0.jd
@@ -104,10 +104,16 @@ sdk.platform.apiLevel=21
</li>
</ol>
-<h2>API 区别</h2>
+<h2>API Differences</h2>
<ol>
-<li><a href="{@docRoot}sdk/api_diff/21/changes.html">API 级别 20 对比 21 »</a> </li>
-<li><a href="{@docRoot}sdk/api_diff/preview-21/changes.html">L Developer Preview 对比级别 21 »</a> </li>
+<li><a href="{@docRoot}sdk/api_diff/21/changes.html">API level 20 to 21 &raquo;</a> </li>
+<li><a href="{@docRoot}sdk/api_diff/preview-21/changes.html">L Developer Preview to 21 &raquo;</a> </li>
+</ol>
+
+<h2>See Also</h2>
+<ol>
+<li><a href="{@docRoot}about/versions/android-5.0-changes.html">Android 5.0 Behavior Changes</a> </li>
+<li><a href="{@docRoot}about/versions/lollipop.html">Android Lollipop Highlights</a> </li>
</ol>
</div>
@@ -628,4 +634,4 @@ $ adb shell dumpsys batterystats --charged &lt;package-name&gt;
<ul>
<li>{@link android.Manifest.permission#BIND_DREAM_SERVICE}:当针对 API 级别 21 和更高级别时,<a href="{@docRoot}about/versions/android-4.2.html#Daydream">Daydream</a> 服务需要此权限来确保只有系统可以绑定到它。</li>
-</ul> \ No newline at end of file
+</ul>
diff --git a/docs/html-intl/intl/zh-tw/about/versions/android-5.0.jd b/docs/html-intl/intl/zh-tw/about/versions/android-5.0.jd
new file mode 100644
index 0000000..6b3637b
--- /dev/null
+++ b/docs/html-intl/intl/zh-tw/about/versions/android-5.0.jd
@@ -0,0 +1,635 @@
+page.title=Android 5.0 API
+excludeFromSuggestions=true
+sdk.platform.version=5.0
+sdk.platform.apiLevel=21
+@jd:body
+
+
+<div id="qv-wrapper">
+<div id="qv">
+
+<h2>本文內容 <a href="#" onclick="hideNestedItems('#toc44',this);return false;" class="header-toggle"> <span class="more">顯示全部</span> <span class="less" style="display:none">顯示主題</span></a></h2>
+
+<ol id="toc44" class="hide-nested">
+ <li><a href="#ApiLevel">更新您的 API 目標等級</a></li>
+ <li><a href="#Behaviors">重要的行為模式異動</a>
+ <ol>
+ <li><a href="#ART">如果您還未在全新的 Android Runtime (ART) 測試您的應用程式...</a></li>
+ <li><a href="#BehaviorNotifications">如果您的應用程式實作了通知功能...</a></li>
+ <li><a href="#BehaviorMediaControl">如果您的應用程式使用了 RemoteControlClient...</a></li>
+<li><a href="#BehaviorGetRecentTasks">如果您的應用程式使用了 getRecentTasks()...</a></li>
+<li><a href="#64BitSupport">如果您使用 Android Native Development Kit (NDK)...</a></li>
+<li><a href="#BindService">如果您的應用程式繫結了其他服務...</a></li>
+<li><a href="#BehaviorWebView">如果您的應用程式使用了 WebView...</a></li>
+ </ol>
+ </li>
+ <li><a href="#UI">使用者介面</a>
+ <ol>
+ <li><a href="#MaterialDesign">實感設計支援</a></li>
+ <li><a href="#Recents">在最近使用項目的螢幕中同時顯示文件和活動</a></li>
+ <li><a href="#WebView">WebView 更新</a></li>
+ <li><a href="#ScreenCapture">螢幕擷取和分享</a></li>
+ </ol>
+ </li>
+ <li><a href="#Notifications">通知</a>
+ <ol>
+ <li><a href="#LockscreenNotifications">鎖定螢幕通知</a></li>
+ <li><a href="#NotificationsMetadata">通知中繼資料</a></li>
+ </ol>
+ </li>
+ <li><a href="#Graphics">顯示</a>
+ <ol>
+ <li><a href="#OpenGLES-3-1">支援 OpenGL ES 3.1</a></li>
+ <li><a href="#AndroidExtensionPack">Android 擴充功能套件</a></li>
+ </ol>
+ </li>
+ <li><a href="#Media">媒體</a>
+ <ol>
+ <li><a href="#Camera-v2">提供進階相機功能的 Camera API</a></li>
+ <li><a href="#AudioPlayback">音訊播放</a></li>
+ <li><a href="#MediaPlaybackControl">媒體播放控制項</a></li>
+ <li><a href="#MediaBrowsing">媒體瀏覽</a></li>
+ </ol>
+ </li>
+ <li><a href="#Storage">儲存空間</a>
+ <ol>
+ <li><a href="#DirectorySelection">目錄選擇</a></li>
+ </ol>
+ </li>
+ <li><a href="#Wireless">無線網路和連線功能</a>
+ <ol>
+ <li><a href="#Multinetwork">可與多個網路連線</a></li>
+ <li><a href="#BluetoothBroadcasting">藍牙廣播</a></li>
+ <li><a href="#NFCEnhancements">NFC 改良</a></li>
+ </ol>
+ </li>
+ <li><a href="#Power">Project Volta</a>
+ <ol>
+ <li><a href="#JobScheduler">排定工作</a></li>
+ <li><a href="#PowerMeasurementTools">監控耗電量的開發人員工具</a>
+ </ol>
+ </li>
+ <li><a href="#Enterprise">Android 在工作和教育方面的應用</a>
+ <ol>
+ <li><a href="#ManagedProvisioning">管理化設定檔建置</a></li>
+ <li><a href="#DeviceOwner">裝置擁有者</a></li>
+ <li><a href="#ScreenPinning">螢幕固定</a></li>
+ </ol>
+ </li>
+ <li><a href="#System">系統</a>
+ <ol>
+ <li><a href="#AppUsageStatistics">應用程式使用統計資料</a></li>
+ </ol>
+ </li>
+ <li><a href="#Printing">列印架構</a>
+ <ol>
+ <li><a href="#PDFRender">將 PDF 轉譯為點陣圖</a></li>
+ </ol>
+ </li>
+ <li><a href="#TestingA11y">測試和協助工具</a>
+ <ol>
+ <li><a href="#TestingA11yImprovements">測試和協助工具改進部分</a></li>
+ </ol>
+ </li>
+ <li><a href="#IME">IME</a>
+ <ol>
+ <li><a href="#Switching">切換輸入語言更輕鬆</a></li>
+ </ol>
+ </li>
+ <li><a href="#Manifest">資訊清單宣告</a>
+ <ol>
+ <li><a href="#ManifestFeatures">可宣告的必要功能</a></li>
+ <li><a href="#Permissions">使用者權限</a></li>
+ </ol>
+ </li>
+</ol>
+
+<h2>API Differences</h2>
+<ol>
+<li><a href="{@docRoot}sdk/api_diff/21/changes.html">API level 20 to 21 &raquo;</a> </li>
+<li><a href="{@docRoot}sdk/api_diff/preview-21/changes.html">L Developer Preview to 21 &raquo;</a> </li>
+</ol>
+
+<h2>See Also</h2>
+<ol>
+<li><a href="{@docRoot}about/versions/android-5.0-changes.html">Android 5.0 Behavior Changes</a> </li>
+<li><a href="{@docRoot}about/versions/lollipop.html">Android Lollipop Highlights</a> </li>
+</ol>
+
+</div>
+</div>
+
+<p>API 等級:{@sdkPlatformApiLevel}</p>
+
+<p>Android 5.0 (<a href="{@docRoot}reference/android/os/Build.VERSION_CODES.html#LOLLIPOP">LOLLIPOP</a>) 為使用者和應用程式開發人員帶來許多全新的功能。本文將為您介紹絕對不容錯過的全新 API。</p>
+
+<p>如要大致瞭解新平台的主要功能,請參閱 <a href="{@docRoot}about/versions/lollipop.html">Android Lollipop 重點介紹</a>。</p>
+
+
+<h3 id="Start">著手開發</h3>
+
+<p>如要開始打造適用於 Android 5.0 的應用程式,您必須先<a href="{@docRoot}sdk/index.html">取得 Android SDK</a>。接著,請使用 <a href="{@docRoot}tools/help/sdk-manager.html">SDK Manager</a> 下載 Android 5.0 SDK 平台和系統映像。</p>
+
+<h3 id="ApiLevel">更新您的 API 目標等級</h3>
+
+<p>如要針對搭載 Android {@sdkPlatformVersion} 的裝置進一步最佳化應用程式,請將 <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> 設為 <code>"{@sdkPlatformApiLevel}"</code>、將應用程式安裝在 Android {@sdkPlatformVersion} 系統映像、詳加測試,然後再發佈更新後的應用程式。</p>
+
+<p>只要在程式碼中新增條件,於執行 <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> 不支援的 API 之前檢查系統 API 等級,您就可以使用 Android {@sdkPlatformVersion} API,同時支援舊版本。如要進一步瞭解維持回溯相容性的方法,請參閱<a href="{@docRoot}training/basics/supporting-devices/platforms.html">支援不同的平台版本</a>。</p>
+
+<p>如要進一步瞭解 API 等級的運作方式,請參閱<a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">什麼是 API 等級?</a></p>
+
+<h2 id="Behaviors">重要的行為模式異動</h2>
+
+<p>如果您曾經發佈適用於 Android 的應用程式,請注意您的應用程式可能會受到 Android 5.0 功能異動的影響。</p>
+
+<h3 id="ART">如果您還未在全新的 Android Runtime (ART) 測試您的應用程式...</h3>
+
+<p>4.4 版導入了全新的實驗性 Android Runtime,簡稱 ART。在 4.4 以下版本,ART 是選用項目,預設執行環境還是 Dalvik。在 Android 5.0 中,ART 現在已成為預設執行環境。</p>
+
+<p>如需 ART 新功能的總覽,請參閱 <a href="https://source.android.com/devices/tech/dalvik/art.html">ART 簡介</a>。以下列出部分主要的新功能:</p>
+
+<ul>
+ <li>預先 (AOT) 編譯</li>
+ <li>改良垃圾資訊收集 (GC) 方法</li>
+ <li>改良偵錯支援</li>
+</ul>
+
+<p>大部分的 Android 應用程式不需任何變更即可在 ART 中運作。不過,仍有部分可支援 Dalvik 的技術無法在 ART 中運作。如需進一步瞭解最重要的問題,請參閱<a href="{@docRoot}guide/practices/verifying-apps-art.html">驗證應用程式在 Android Runtime (ART) 的行為</a>。如果應用程式符合下列情形,請特別留意:</p>
+
+<ul>
+ <li>您的應用程式使用 Java Native Interface (JNI) 執行 C/C++ 程式碼。</li>
+ <li>您使用產生非標準程式碼 (例如部分擾亂器) 的開發工具。</li>
+ <li>您使用的技術與精簡垃圾資訊收集方法不相容 (ART 目前未實作精簡 GC,但是 Android 開放原始碼專案已在進行相關開發工作)。</li>
+</ul>
+
+<h3 id="BehaviorNotifications">如果您的應用程式實作了通知功能...</h3>
+
+<p>在實作通知功能時,請務必瞭解相關的 Android 5.0 異動部分會造成什麼影響。如要進一步瞭解如何設計適用於 Android 5.0 以上版本的通知功能,請參閱<a href="{@docRoot}design/patterns/notifications.html">通知功能設計指南</a>。
+</p>
+
+<h4 id="NotificationsMaterialDesignStyle">實感設計樣式</h4>
+<p>為配合新的實感設計 (Material Design) 小工具的風格,通知會以深色文字搭配白色 (或非常淺色) 的背景呈現。請確認所有的通知都符合全新的配色規範。如果通知的配色不符合上述規範,請透過下列方法修正:</p>
+
+<ul>
+ <li>使用 {@link android.app.Notification.Builder#setColor(int) setColor()} 為圖示影像後的圓圈設定強調色。 </li>
+ <li>更新或移除任何與顏色相關的資產。系統會忽略動作圖示和主要通知圖示中 Alpha 以外的所有通道。建議您假設這些圖示都只具備 Alpha 通道。系統會以白色繪製通知圖示,而以深灰色繪製動作圖示。</li>
+</ul>
+
+<h4 id="NotificationsSoundVibration">音效和震動</h4>
+<p>如果您目前是使用 {@link android.media.Ringtone}、{@link android.media.MediaPlayer} 或 {@link android.os.Vibrator} 類別為通知新增音效和震動功能,請移除這個程式碼,以便系統可以「優先」<em></em>模式正確呈現通知。然後,請改用 {@link android.app.Notification.Builder} 方法新增音效和震動功能。</p>
+
+<p>如果將裝置設定為 {@link android.media.AudioManager#RINGER_MODE_SILENT RINGER_MODE_SILENT},裝置會進入新的優先模式。如果您將裝置設定為 {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_NORMAL} 或 {@link android.media.AudioManager#RINGER_MODE_NORMAL RINGER_MODE_VIBRATE},裝置則會結束優先模式。</p>
+
+<p>Android 之前使用 {@link android.media.AudioManager#STREAM_MUSIC STREAM_MUSIC} 做為控制平板電腦音量的主要串流。在 Android 5.0 中,手機和平板電腦的主要音量串流已經統一由 {@link android.media.AudioManager#STREAM_RING STREAM_RING} 或 {@link android.media.AudioManager#STREAM_NOTIFICATION STREAM_NOTIFICATION} 控制。</p>
+
+<h4 id="NotificationsLockscreenVisibility">鎖定螢幕可見度</h4>
+<p>根據 Android 5.0 預設設定,通知現在會顯示在使用者的鎖定螢幕。使用者可以選擇隱藏敏感的資訊,如此系統就會自動覆蓋通知顯示的文字。如要自訂具備覆蓋功能的通知,請使用 {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()}。</p>
+<p>如果通知並未包含個人資訊,或者如果您要啟用通知中的媒體播放控制項,請呼叫 {@link android.app.Notification.Builder#setVisibility(int) setVisibility()} 方法,然後將通知可見度等級設為 {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}。
+</p>
+
+<h4 id="NotificationsMediaPlayback">媒體播放</h4>
+<p>如果您要實作會呈現媒體播放狀態或傳輸控制項的通知,不妨考慮使用全新的 {@link android.app.Notification.MediaStyle} 範本,而不是自訂的 {@link android.widget.RemoteViews.RemoteView}。無論您選擇哪一種方法,請確認將通知可見度設為 {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC},如此才可在鎖定螢幕使用控制項。請注意從 Android 5.0 開始,系統不會再將 {@link android.media.RemoteControlClient} 物件顯示在鎖定螢幕。詳情參閱<a href="#BehaviorMediaControl">如果您的應用程式使用了 RemoteControlClient</a>一節的說明。</p>
+
+<h4 id="NotificationsHeadsup">提醒通知</h4>
+<p>當裝置處於使用中狀態 (裝置鎖定但顯示螢幕),通知現在會顯示在小型浮動視窗 (也稱為提醒通知)。提醒通知看起來很像精簡版的通知,只是另外還會顯示動作按鈕。使用者不需要離開目前的應用程式即可操作或關閉提醒通知。</p>
+
+<p>以下列出會觸發提醒通知的條件:</p>
+
+<ul>
+ <li>使用者活動目前以全螢幕顯示 (應用程式使用 {@link android.app.Notification#fullScreenIntent})</li>
+ <li>通知具有高優先級,並使用鈴聲或震動</li>
+</ul>
+
+<p>如果您的應用程式在上述情況實作通知,請確認提醒通知可以正確顯示。</p>
+
+<h3 id="BehaviorMediaControl">如果您的應用程式使用了 RemoteControlClient...</h3>
+<p>{@link android.media.RemoteControlClient} 類別現在已淘汰。請儘快改用全新的 {@link android.media.session.MediaSession} API。</p>
+
+<p>Android 5.0 的鎖定螢幕不會為您的 {@link android.media.session.MediaSession} 或 {@link android.media.RemoteControlClient} 顯示傳輸控制項。但是,您的應用程式可以透過通知在鎖定螢幕提供媒體播放控制項。您的應用程式可因此全權掌控媒體按鈕的呈現方式,無論裝置鎖定與否,使用者也可獲得一致的體驗。</p>
+
+<p>為達到這個目標,Android 5.0 特別導入了全新的 {@link android.app.Notification.MediaStyle} 範本。{@link android.app.Notification.MediaStyle} 會將您透過 {@link android.app.Notification.Builder#addAction(int, java.lang.CharSequence, android.app.PendingIntent) Notification.Builder.addAction()} 新增的通知動作轉換為內嵌在應用程式媒體播放通知的精簡按鈕。接著,再將工作階段符記傳遞到 {@link android.app.Notification.MediaStyle#setMediaSession(android.media.session.MediaSession.Token) setSession()} 方法,告知系統這個通知會控制進行中的媒體工作階段。</p>
+
+<p>請務必將通知的可見度設為 {@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC},表示通知內容可顯示在任何鎖定螢幕 (無論是否完成安全設定皆可)。如需詳細資訊,請參閱<a href="#LockscreenNotifications">鎖定螢幕通知</a>。</p>
+
+<p>如果您的應用程式是在 Android <a href="{@docRoot}tv/index.html">TV</a> 或 <a href="{@docRoot}wear/index.html">Wear</a> 平台執行,而您想要顯示媒體播放控制項,請實作 {@link android.media.session.MediaSession} 類別。如果您的應用程式需要接收 Android 裝置上的媒體按鈕事件,建議您同時實作 {@link android.media.session.MediaSession}。</p>
+
+<h3 id="BehaviorGetRecentTasks">如果您的應用程式使用了 getRecentTasks()...</h3>
+
+<p>Android 5.0 推出了「同時顯示文件和活動工作」<em></em>的新功能 (請參閱下方的<a href="#Recents">在最近使用項目的螢幕中同時顯示文件和活動</a>),因此我們已淘汰 {@link android.app.ActivityManager#getRecentTasks ActivityManager.getRecentTasks()} 方法,以便提升對使用者隱私的保護強度。為提供回溯相容性,這個功能仍會傳回一小部分資料,包含發出呼叫的應用程式的工作,以及其他非敏感性的工作 (例如主畫面)。如果您的應用程式目前使用這個方法擷取所屬的工作,請改用 {@link android.app.ActivityManager#getAppTasks() getAppTasks()} 擷取這項資訊。</p>
+
+<h3 id="64BitSupport">如果您使用 Android Native Development Kit (NDK)...</h3>
+
+<p>Android 5.0 支援 64 位元的系統。64 位元改良功能可增加地址空間並提升效能,同時仍可完整支援現有的 32 位元應用程式。對於 64 位元系統的支援也可改善 OpenSSL 的加密效能。此外,這個版本也導入了全新的原生媒體 NDK API 和原生 OpenGL ES (GLES) 3.1 支援。</p>
+
+<p>如要使用 Android 5.0 的 64 位元支援功能,請前往 <a href="{@docRoot}tools/sdk/ndk/index.html">Android NDK 頁面</a>下載並安裝 NDK Revision 10c。如要瞭解 NDK 的重要異動和錯誤修正資訊,請參閱 Revision 10c <a href="{@docRoot}tools/sdk/ndk/index.html#Revisions">版本資訊</a>。</p>
+
+<h3 id="BindService">如果您的應用程式繫結了其他服務...</h3>
+
+<p>{@link android.content.Context#bindService(android.content.Intent, android.content.ServiceConnection, int) Context.bindService()} 方法現在會要求明確指定的 {@link android.content.Intent};如果收到隱式調用請求,則會擲回例外狀況。為確保您的應用程式安全無虞,在啟動或繫結 {@link android.app.Service} 時,請使用明確指定的調用請求,同時請勿針對服務宣告調用請求篩選器。</p>
+
+<h3 id="BehaviorWebView">如果您的應用程式使用了 WebView...</h3>
+
+<p>Android 5.0 變更了應用程式的預設行為。</p>
+<ul>
+<li><strong>如果您的應用程式的 API 目標等級為 21 以上:</strong>
+ <ul>
+ <li>在預設情況下,系統會封鎖<a href="https://developer.mozilla.org/en-US/docs/Security/MixedContent" class="external-link">混合內容</a>和第三方 Cookie。如要允許混合內容和第三方 Cookie,請分別使用 {@link android.webkit.WebSettings#setMixedContentMode(int) setMixedContentMode()} 和 {@link android.webkit.CookieManager#setAcceptThirdPartyCookies(android.webkit.WebView, boolean) setAcceptThirdPartyCookies()}·方法。</li>
+ <li>系統現在可精確擷取 HTML 文件的部分內容。這個全新的預設行為有助於降低記憶體足跡並有效提升效能。如果您要轉譯整份文件,請呼叫 {@link android.webkit.WebView#enableSlowWholeDocumentDraw()} 以停用這項最佳化行為。</li>
+ </ul>
+</li>
+<li><strong>如果您的應用程式指定 API 等級 21 以下:</strong>根據預設,系統會允許混合內容和第三方 Cookie,並一律轉譯整份文件。</li>
+</ul>
+
+<h2 id="UI">使用者介面</h2>
+
+<h3 id="MaterialDesign">實感設計支援</h3>
+
+<p>在即將發行的版本中,我們開始支援新採用的 Android 實感設計 (Material Design) 樣式。<em></em>您可以使用實感設計機制來開發您的應用程式,為使用者提供充滿動感且流暢的使用者介面元素轉換效果。這項支援包含:</p>
+
+<ul>
+
+ <li>實感主題</li>
+ <li>檢視畫面陰影</li>
+ <li>{@link android.support.v7.widget.RecyclerView} 小工具</li>
+ <li>可繪項目的動畫和樣式效果</li>
+ <li>實感設計動畫和活動轉換效果</li>
+ <li>依據檢視畫面狀態提供檢視畫面屬性的動畫</li>
+ <li>可自訂的使用者介面小工具和應用程式列 (附有可控制的調色盤)</li>
+ <li>依據 XML 向量圖形的動畫和非動畫可繪項目</li>
+</ul>
+
+<p>如要進一步瞭解如何為您的應用程式加入實感設計功能,請參閱<a href="{@docRoot}training/material/index.html">實感設計</a>一節的介紹。</p>
+
+<h3 id="Recents">在最近使用項目的螢幕中同時顯示文件和活動</h3>
+
+<p>在先前的版本中,對於使用者最近互動的每一個應用程式,<a href="{@docRoot}guide/components/recents.html">最近使用項目的螢幕</a>只會顯示一個工作。現在,您的應用程式會視情況開啟更多工作,協助您掌握文件的同步執行活動。這項功能可提升多工作業效能,因為使用者可在最近使用項目的螢幕中快速切換各個活動和文件,而且在所有應用程式都可享有一致的切換體驗。舉例來說,這類同時執行的工作包含:網路瀏覽器應用程式中同時開啟的分頁、生產力應用程式中的文件、遊戲中同時執行的比賽,或是簡訊應用程式中的通訊活動。您的應用程式可以透過 {@link android.app.ActivityManager.AppTask} 類別·管理工作。</p>
+
+<p>如要插入邏輯中斷點告知系統將您的活動視為新工作,當您透過 {@link android.app.Activity#startActivity(android.content.Intent) startActivity()} 啟動活動時,請使用 {@link android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT}。如要獲得這項行為,您也可以在資訊清單中將 <a href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a> 元素的 {@code documentLaunchMode} 屬性設定為 {@code "intoExisting"} 或 {@code "always"}。</p>
+
+<p>為避免最近使用項目的螢幕過於擁擠,不妨設定可在這個螢幕中顯示的應用程式工作上限。如要這麼做,請設定 <a href="{@docRoot}guide/topics/manifest/application-element.html">&lt;application&gt;</a> 屬性的 {@link android.R.attr#maxRecents android:maxRecents}。目前的上限是每位使用者最多可以顯示 50 個工作 (RAM 較低的裝置則為 25 個)。</a></p>
+
+<p>對於最近使用項目螢幕中的工作,您可以進行設定,讓這些工作在重新開機後持續顯示。如要控制持續顯示行為,請使用 <a href="{@docRoot}reference/android/R.attr.html#persistableMode">android:persistableMode</a> 屬性。對於最近使用項目螢幕中的活動,您也可以變更視覺屬性,例如活動的顏色、標籤和圖示,只要呼叫 {@link android.app.Activity#setTaskDescription(android.app.ActivityManager.TaskDescription) setTaskDescription()} 方法即可。</p>
+
+<h3 id="WebView">WebView 更新</h3>
+<p>Android 5.0 已將 {@link android.webkit.WebView} 實作更新為 Chromium M37,不僅提升安全性和穩定性,同時也修正了多項錯誤。在 Android 5.0 執行的 {@link android.webkit.WebView} 預設使用者代理程式字串也已更新,目前包含 37.0.0.0 版本資訊。</p>
+
+<p>這個版本導入了 {@link android.webkit.PermissionRequest} 類別,可讓您的應用程式授予 {@link android.webkit.WebView} 權限,以便透過 <a href="https://developer.mozilla.org/en-US/docs/NavigatorUserMedia.getUserMedia" class="external-link">getUse Media()</a> 等 Web API 存取受保護的資源 (例如相機和麥克風)。對於這些資源,您的應用程式必須具備適當的 Android 權限,才可將權限授予 {@link android.webkit.WebView}。</p>
+
+<p>透過全新的 <code><a href="{@docRoot}reference/android/webkit/WebChromeClient.html#onShowFileChooser(android.webkit.WebView, android.webkit.ValueCallback<android.net.Uri[]>, android.webkit.WebChromeClient.FileChooserParams)">onShowFileChooser()</a></code> 方法,您現在可以使用 {@link android.webkit.WebView} 中的輸入表單欄位,並啟動檔案選擇器選取 Android 裝置中的圖片和檔案。</p>
+
+<p>此外,這個版本也新增了 <a href="http://webaudio.github.io/web-audio-api/" class="external-link">WebAudio</a>、<a href="https://www.khronos.org/webgl/" class="external-link">WebGL</a> 和 <a href="http://www.webrtc.org/" class="external-link">WebRTC</a> 開放標準的支援功能。如要進一步瞭解這個版本中的全新功能,請參閱<a href="https://developer.chrome.com/multidevice/webview/overview" class="external-link">適用於 Android 的 WebView</a>。</p>
+
+<h3 id="ScreenCapture">螢幕擷取和分享</h3>
+<p>Android 5.0 可讓您透過 {@link android.media.projection} API,將螢幕擷取和分享功能新增到應用程式。舉例來說,如果您想在視訊會議應用程式中啟用螢幕分享功能,這項功能就可派上用場。</p>
+
+<p>全新的 {@link android.media.projection.MediaProjection#createVirtualDisplay(java.lang.String, int, int, int, int, android.view.Surface, android.hardware.display.VirtualDisplay.Callback, android.os.Handler) createVirtualDisplay()} 方法可讓您的應用程式將主螢幕的內容 (預設畫面) 擷取到 {@link android.view.Surface} 物件,方便稍後傳送到網路。這個 API 只允許擷取未經過安全設定的螢幕內容,而且也不能擷取系統音訊。如要開始擷取螢幕,您的應用程式必須先使用 {@link android.media.projection.MediaProjectionManager#createScreenCaptureIntent()} 方法取得 {@link android.content.Intent},藉此啟動螢幕擷取對話方塊要求使用者的權限。</p>
+
+<p>如需全新 API 的使用示例,請參閱範例專案中的 {@code MediaProjectionDemo} 類別。</p>
+
+<h2 id="Notifications">通知</h2>
+
+<h3 id="LockscreenNotifications">鎖定螢幕通知</h3>
+<p>Android 5.0 的鎖定螢幕可顯示通知。透過「設定」<em></em>,使用者可選擇是否要允許敏感的通知內容顯示在安全的鎖定螢幕。</p>
+
+<p>當通知內容顯示在安全的鎖定螢幕時,您的應用程式可控制要顯示多少內容。如要控制可見度等級,請呼叫 {@link android.app.Notification.Builder#setVisibility(int) setVisibility()} 並指定下列其中一個值:</p>
+
+<ul>
+<li>{@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}:顯示基本資訊 (例如通知的圖示),但隱藏通知的完整內容。</li>
+<li>{@link android.app.Notification#VISIBILITY_PUBLIC VISIBILITY_PUBLIC}:顯示通知的完整內容。</li>
+<li>{@link android.app.Notification#VISIBILITY_SECRET VISIBILITY_SECRET}:不顯示任何資訊,即使是通知的圖示也不顯示。</li>
+</ul>
+
+<p>當可見度等級為 {@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE} 時,您也可以提供覆蓋個人資訊的通知內容。舉例來說,簡訊應用程式可能會顯示「您有 3 則新簡訊」的通知,但是隱藏簡訊內容和寄件者。如要提供這類通知,請先使用 {@link android.app.Notification.Builder} 建立替代通知。當您建立私人通知物件時,請透過 {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()} 方法附加替代通知。</p>
+
+<h3 id="NotificationsMetadata">通知中繼資料</h3>
+<p>Android 5.0 會使用與您應用程式通知相關聯的中繼資料,精確分類各項通知。如要設定中繼資料,當您建構通知時,請在 {@link android.app.Notification.Builder} 呼叫下列方法:</p>
+
+<ul>
+<li>{@link android.app.Notification.Builder#setCategory(java.lang.String) setCategory()}:告知系統當裝置為「優先」<em></em>模式時應如何處理應用程式通知 (例如,通知代表來電、即時訊息或鬧鐘時的處理方式)。
+<li>{@link android.app.Notification.Builder#setPriority(int) setPriority()}:標示這個通知的重要性 (與 般通知相比)。如果通知的優先欄位設為 {@link android.app.Notification#PRIORITY_MAX PRIORITY_MAX} 或 {@link android.app.Notification#PRIORITY_HIGH PRIORITY_HIGH},同時也具有音效和震動,則會顯示在小型浮動視窗。</li>
+<li>{@link android.app.Notification.Builder#addPerson(java.lang.String) addPerson()}:讓您新增一或多個與通知相關的使用者。您的應用程式可以使用這個方法,告知系統應將指定使用者傳來的通知歸類在一起,或是將這些使用者傳來的通知優先顯示。</li>
+</ul>
+
+<h2 id="Graphics">顯示</h2>
+
+<h3 id="OpenGLES-3-1">支援 OpenGL ES 3.1</h3>
+<p>Android 5.0 新增了 Java 介面和 OpenGL ES 3.1 原生支援。OpenGL ES 3.1 主要的新功能包含:</p>
+
+<ul>
+<li>運算著色器
+<li>獨立的著色器物件
+<li>間接繪製指令
+<li>多個範例和型染紋理
+<li>著色語言改良
+<li>進階混合模式和偵錯擴充功能
+<li>與 OpenGL ES 2.0 和 3.0 回溯相容
+</ul>
+
+<p>適用於 Android 版 OpenGL ES 3.1 的 Java 介面是透過 {@link android.opengl.GLES31} 提供。使用 OpenGL ES 3.1 時,請確認您透過 <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> 標記和 {@code android:glEsVersion} 屬性,在資訊清單檔案中宣告。例如:</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:glEsVersion="0x00030001" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<p>如需使用 OpenGL ES 的詳細資訊 (包含在執行時間檢查裝置支援的 OpenGL ES 版本),請參閱 <a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL ES API 指南</a>。</p>
+
+<h3 id="AndroidExtensionPack">Android 擴充功能套件</h3>
+
+<p>除了 OpenGL ES 3.1,這個版本還提供包含 Java 介面的擴充功能套件和進階圖型功能的原生支援。Android 會將這些擴充功能視為單一套件 (如果 {@code ANDROID_extension_pack_es31a} 擴充功能存在,您的應用程式就會假設套件中的所有擴充功能都存在,並透過單一 {@code #extension} 陳述式啟用著色語言功能)。</p>
+
+<p>擴充功能套件支援:</p>
+
+<ul>
+<li>對於著色器儲存空間緩衝區、圖片和原子圖像提供保證的片段著色器支援 (OpenGL ES 3.1 中的片段著色器支援是選擇性的)。</li>
+<li>曲面細分和幾何圖形著色器</li>
+<li>ASTC (LDR) 紋理壓縮格式</li>
+<li>取樣差補和著色</li>
+<li>在影格緩衝區中,每個顏色附件可以具有不同的混合模式</li>
+</ul>
+
+<p>適用於擴充功能的 Java 介面是透過 {@link android.opengl.GLES31Ext} 提供。在您的應用程式資訊清單中,您可以宣告應用程式必須安裝在支援擴充功能的裝置。例如:</p>
+
+<pre>
+&lt;manifest&gt;
+ &lt;uses-feature android:name=“android.hardware.opengles.aep”
+ android:required="true" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<h2 id="Media">媒體</h2>
+
+<h3 id="Camera-v2">提供進階相機功能的 Camera API</h3>
+
+<p>Android 5.0 導入了全新的 <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">android.hardware.camera2</a> API,可提供更精細的相片拍攝和圖片處理功能。您現在可以透過 {@link android.hardware.camera2.CameraManager#getCameraIdList() getCameraIdList()},以程式方式存取系統可用的相機裝置,並透過 {@link android.hardware.camera2.CameraManager#openCamera(java.lang.String, android.hardware.camera2.CameraDevice.StateCallback, android.os.Handler) openCamera()} 連接特定的裝置。如要開始拍攝影像,請建立 {@link android.hardware.camera2.CameraCaptureSession} 並指定 {@link android.view.Surface} 物件,以傳送拍攝的影像。您可以將 {@link android.hardware.camera2.CameraCaptureSession} 設定為拍攝單張相片或連續拍攝多張相片。</p>
+
+<p>如果希望系統在拍攝新影像時通知您,請實作 {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} 監聽器,並在拍攝要求中設定。設定完成後,當系統完成影像拍攝要求時,您的 {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} 監聽器就會收到針對 {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback#onCaptureCompleted(android.hardware.camera2.CameraCaptureSession, android.hardware.camera2.CaptureRequest, android.hardware.camera2.TotalCaptureResult) onCaptureCompleted()} 的呼叫,透過 {@link android.hardware.camera2.CaptureResult} 為您提供影像拍攝中繼資料。</p>
+
+<p>{@link android.hardware.camera2.CameraCharacteristics} 類別可讓您的應用程式偵測裝置可用的相機功能。物件的 {@link android.hardware.camera2.CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL INFO_SUPPORTED_HARDWARE_LEVEL} 屬性代表相機的功能等級。</p>
+
+<ul>
+ <li>所有的裝置至少都支援 {@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY} 硬體等級,具備的功能大概等同已淘汰的 {@link android.hardware.Camera} API。</li>
+ <li>支援 {@link android.hardware.camera2.CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_FULL INFO_SUPPORTED_HARDWARE_LEVEL_FULL} 硬體等級的裝置具備手動拍攝和後製處理的控制功能,並可以高影格速率拍攝高解析度的影像。</li>
+</ul>
+
+<p>如要瞭解更新版 <a href="{@docRoot}reference/android/hardware/camera2/package-summary.html">Camera</a> API 的使用方法,請參閱這個版本的 {@code Camera2Basic} 和 {@code Camera2Video} 實作示例。</p>
+
+<h3 id="AudioPlayback">音訊播放</h3>
+<p>這個版本包括下列與 {@link android.media.AudioTrack} 相關的變更:</p>
+<ul>
+ <li>您的應用程式現在可以透過浮點格式提供音訊資料 ({@link android.media.AudioFormat#ENCODING_PCM_FLOAT ENCODING_PCM_FLOAT})。這麼做可獲得更大的動態範圍、更一致的精準度,以及更高的音訊極限。在進行中間計算時,浮點算術特別實用。對於音訊資料,播放端點會使用整數格式,並採用較低的位元深度 (在 Android 5.0 中,部分的內部管道還不是浮點)。
+ <li>您的應用程式現在可以使用 {@link java.nio.ByteBuffer} 提供音訊資料,與 {@link android.media.MediaCodec}·提供的格式相同。
+ <li>{@link android.media.AudioTrack#WRITE_NON_BLOCKING WRITE_NON_BLOCKING} 選項可以簡化部分應用程式的緩衝和多執行緒處理程序。
+</ul>
+
+<h3 id="MediaPlaybackControl">媒體播放控制項</h3>
+<p>使用全新的通知和媒體 API,即可確保系統使用者介面認得您的媒體播放作業,並可擷取即顯示專輯圖片。現在,只要使用全新的 {@link android.media.session.MediaSession} 和 {@link android.media.session.MediaController}·類別,您即可在使用者介面和服務輕鬆控制媒體播放作業。</p>
+
+<p>全新的 {@link android.media.session.MediaSession} 類別取代了已淘汰的 {@link android.media.RemoteControlClient} 類別,並提供一組回呼方法處理傳輸控制項和媒體按鈕。如果您的應用程式提供媒體播放功能並可在 Android <a href="{@docRoot}tv/index.html">TV</a>或 <a href="{@docRoot}wear/index.html">Wear</a> 平台執行,請使用 {@link android.media.session.MediaSession}·類別處理採用相同回呼方法的傳輸控制項。</p>
+
+<p>您現在可以使用全新的 {@link android.media.session.MediaController} 類別打造專屬的媒體控制應用程式。這個類別提供對執行緒安全的方式,監控及控制來自您的應用程式使用者介面程序的媒體播放作業。建立控制項時,請指定 {@link android.media.session.MediaSession.Token} 物件,以便應用程式可以與 {@link android.media.session.MediaSession} 互動。透過使用 {@link android.media.session.MediaController.TransportControls} 方法,您可以傳送 {@link android.media.session.MediaController.TransportControls#play() play()}、{@link android.media.session.MediaController.TransportControls#stop() stop()}、{@link android.media.session.MediaController.TransportControls#skipToNext() skipToNext()} 和 {@link android.media.session.MediaController.TransportControls#setRating(android.media.Rating) setRating()} 等指令,以控制該工作階段的媒體播放作業。您也可以運用這個控制項註冊 {@link android.media.session.MediaController.Callback} 物件,以便監聽中繼資料並在該工作階段陳述變更。</p>
+
+<p>此外,您可以使用全新的 {@link android.app.Notification.MediaStyle} 類別建立功能豐富的通知,允許播放控制項與媒體工作階段連結。</p>
+
+<h3 id="MediaBrowsing">媒體瀏覽</h3>
+<p>Android 5.0 導入了新功能,可讓應用程式透過 <a href="{@docRoot}reference/android/media/browse/package-summary.html">android.media.browse</a> API 瀏覽其他應用程式的媒體內容庫。如要公開您應用程式的媒體內容,請擴展 {@link android.service.media.MediaBrowserService} 類別。實作 {@link android.service.media.MediaBrowserService} 後應可提供 {@link android.media.session.MediaSession.Token} 的存取權,以便應用程式播放透過您的服務提供的媒體內容。</p>
+<p>如要與媒體瀏覽器服務互動,請使用 {@link android.media.browse.MediaBrowser} 類別。建立 {@link android.media.browse.MediaBrowser} 執行個體時,請指定 {@link android.media.session.MediaSession} 的元件名稱。使用該瀏覽器執行個體時,您的應用程式即可連結到相關的服務並獲得 {@link android.media.session.MediaSession.Token} 物件,以便播放該服務公開的內容。</p>
+
+<h2 id="Storage">儲存空間</h2>
+
+<h3 id="DirectorySelection">目錄選擇</h3>
+
+<p>Android 5.0 已擴展<a href="{@docRoot}guide/topics/providers/document-provider.html">儲存空間存取架構</a>,現在可讓使用者選取整個目錄子樹狀結構,應用程式不需要使用者逐一確認,即可獲得讀取/寫入其中所有文件的權限。</p>
+
+<p>如要選取目錄子樹狀結構,請建構並傳送 {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE OPEN_DOCUMENT_TREE} 調用請求。系統會顯示所有支援子樹狀結構選取功能的 {@link android.provider.DocumentsProvider} 執行個體,方便使用者瀏覽及選取目錄。傳回 URI 代表您可存取所選的子樹狀結構。這時您就可以使用 {@link android.provider.DocumentsContract#buildChildDocumentsUriUsingTree(android.net.Uri, java.lang.String) buildChildDocumentsUriUsingTree()}、{@link android.provider.DocumentsContract#buildDocumentUriUsingTree(android.net.Uri, java.lang.String) buildDocumentUriUsingTree()} 和 {@link android.content.ContentResolver#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String) query()} 探索子樹狀結構。</p>
+
+<p>全新的 {@link android.provider.DocumentsContract#createDocument(android.content.ContentResolver, android.net.Uri, java.lang.String, java.lang.String) createDocument()} 方法可讓您在子樹狀結構的任何位置建立新文件或目錄。如要管理現有的文件,請使用 {@link android.provider.DocumentsContract#renameDocument(android.content.ContentResolver, android.net.Uri, java.lang.String) renameDocument()} 和 {@link android.provider.DocumentsProvider#deleteDocument(java.lang.String) deleteDocument()}。發出呼叫前,請檢查 {@link android.provider.DocumentsContract.Document#COLUMN_FLAGS COLUMN_FLAGS} 以確認提供者支援這些呼叫。</p>
+
+<p>如果您正在實作 {@link android.provider.DocumentsProvider} 且想要支援子樹狀結構選取功能,請實作 {@link android.provider.DocumentsProvider#isChildDocument(java.lang.String, java.lang.String) isChildDocument()},並將 {@link android.provider.DocumentsContract.Root#FLAG_SUPPORTS_IS_CHILD FLAG_SUPPORTS_IS_CHILD} 納入您的 {@link android.provider.DocumentsContract.Root#COLUMN_FLAGS COLUMN_FLAGS}。</p>
+
+<p>Android 5.0 也在共用儲存空間導入了全新的套件專屬目錄,您的應用程式可將要納入 {@link android.provider.MediaStore} 的媒體檔案放在其中。全新的 {@link android.content.Context#getExternalMediaDirs()} 會傳回前往所有共用儲存空間裝置上的目錄路徑。與 {@link android.content.Context#getExternalFilesDir(java.lang.String) getExternalFilesDir()} 相似,您的應用程式不需要額外權限即可存取傳回的路徑。這個平台會定期掃描這些目錄中的新媒體,但您也可以使用 {@link android.media.MediaScannerConnection} 自行掃描新內容。</p>
+
+<h2 id="Wireless">無線網路和連線功能</h2>
+
+<h3 id="Multinetwork">可與多個網路連線</h3>
+<p>Android 5.0 提供全新的多網路連線 API,可讓您的應用程式動態掃描可用且具備特定功能的網路,進而建立連線。當您的應用程式需要具備特定功能的網路 (例如 SUPL、MMS 或電信代扣結帳網路),或是您想要使用特定類型的傳輸通訊協定傳送資料,這項功能就能派上用場。</p>
+
+<p>如要從您的應用程式動態選取及連接網路,請按照下列步驟進行:</p>
+
+<ol>
+ <li>建立 {@link android.net.ConnectivityManager}。</li>
+ <li>使用 {@link android.net.NetworkRequest.Builder} 類別建立 {@link android.net.NetworkRequest} 物件,然後指定您的應用程式偏好的網路功能和傳輸類型。</li>
+<li>如要掃描適用的網路,請呼叫 {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} 或 {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()},然後傳遞 {@link android.net.NetworkRequest} 物件和 {@link android.net.ConnectivityManager.NetworkCallback} 實作。如果您希望系統偵測到適用網路時主動切換,請使用 {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) requestNetwork()} 方法。如果只想收到適用網路的通知 (不要主動切換),請使用 {@link android.net.ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback) registerNetworkCallback()} 方法。</li>
+</ol>
+
+<p>當系統偵測到適用網路時,就會自動連線並叫用 {@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()} 回呼。您可以使用回呼的 {@link android.net.Network} 物件,以取得網路的額外資訊,或是將流量導向所選的網路。</p>
+
+<h3 id="BluetoothBroadcasting">藍牙低功耗技術</h3>
+<p>Android 4.3 平台首度導入了<a href="{@docRoot}guide/topics/connectivity/bluetooth-le.html">藍牙低功耗技術</a> (<em>Bluetooth LE</em>) 支援功能,讓裝置以主機角色建立連線。在 Android 5.0 中,Android 裝置則可以扮演 Bluetooth LE「周邊裝置」<em></em>的角色。應用程式可以透過這項功能,輕鬆讓附近的裝置偵測到。舉例來說,您可以打造應用程式,讓裝置化身為計步器或健康監測器,並將資料傳送給另一台 Bluetooth LE 裝置。</p>
+<p>全新的 {@link android.bluetooth.le} API 可讓您的應用程式播送廣告、掃描回應,以及與附近的 Bluetooth LE 裝置建立連線。如要使用全新的廣告和掃描功能,請在您的資訊清單中新增 {@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN} 權限。當使用者從 Play 商店更新或下載您的應用程式時,會看到以下的權限要求提示:「藍牙連線資訊:允許應用程式控制藍牙功能,包括對附近的藍牙裝置播送資訊,或是從附近的藍牙裝置取得資訊。」</p>
+
+<p>如要開始 Bluetooth LE 廣告功能,以便其他裝置發掘您的應用程式,請呼叫 {@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()} 並傳遞 {@link android.bluetooth.le.AdvertiseCallback} 類別實作。回呼物件會收到廣告作業成功或失敗的報告。</p>
+
+<p> Android 5.0 導入了 {@link android.bluetooth.le.ScanFilter} 類別,因此您的應用程式可以只掃描偏好的特定裝置類型。如要開始掃描 Bluetooth LE 裝置,請呼叫 {@link android.bluetooth.le.BluetoothLeScanner#startScan(android.bluetooth.le.ScanCallback) startScan()} 並傳遞篩選器清單。在方法呼叫中,您也必須提供 {@link android.bluetooth.le.ScanCallback} 實作,以便系統在發現 Bluetooth LE·裝置時向您回報。 </p>
+
+<h3 id="NFCEnhancements">NFC 改良</h3>
+<p>Android 5.0 新增了改良措施,讓 NFC 的用途更廣更靈活。</p>
+
+<ul>
+<li>您現在可以在「分享」選單中找到 Android Beam<em></em>。</li>
+<li>透過呼叫 {@link android.nfc.NfcAdapter#invokeBeam(android.app.Activity) invokeBeam()},您的應用程式可以在使用者的裝置叫用 Android Beam 來分享資料。如此一來,使用者不必將裝置與另一台具備 NFC 功能的裝置實際接觸,即可完成資料傳輸。</li>
+<li>您可以使用全新的 {@link android.nfc.NdefRecord#createTextRecord(java.lang.String, java.lang.String) createTextRecord()} 方法來建立包含 UTF-8·文字資料的 NDEF 紀錄。</li>
+<li>如果您正在開發付款應用程式,現在可以透過呼叫 <code><a href="{@docRoot}reference/android/nfc/cardemulation/CardEmulation.html#registerAidsForService(android.content.ComponentName, java.lang.String, java.util.List<java.lang.String>)">registerAidsForService()</a></code> 的方式,動態註冊 NFC 應用程式 ID (AID)。您也可以使用 {@link android.nfc.cardemulation.CardEmulation#setPreferredService(android.app.Activity, android.content.ComponentName) setPreferredService()},針對前景的特定活動設定應該使用的偏好卡片模擬服務。</li>
+</ul>
+
+<h2 id="Power">Project Volta</h2>
+
+<p>除了導入新功能之外,Android 5.0 也很重視如何提升電池電力方面的效能。建議您不妨使用全新的 API 和工具,瞭解應用程式的耗電量並進行最佳化。</p>
+
+<h3 id="JobScheduler">排定工作</h3>
+<p>Android 5.0 提供了全新的 {@link android.app.job.JobScheduler} API,可讓您為系統定義稍後執行的非同步工作或是在特定條件下 (例如裝置充電時) 執行的工作,進而將電池電力最佳化。對於下列情況來說,工作安排功能特別實用:</p>
+<ul>
+ <li>應用程式包含使用者不會看到且可以延後執行的工作。</li>
+ <li>應用程式包含您希望裝置充電時再執行的工作。</li>
+ <li>應用程式包含需要網路或 Wi-Fi 連線的工作。</li>
+ <li>應用程式包含您希望定期批次執行的多個工作。</li>
+
+</ul>
+
+<p>每一個工作單元都封裝在 {@link android.app.job.JobInfo} 物件中,這個物件會指定各項安排條件。</p>
+
+<p>請使用 {@link android.app.job.JobInfo.Builder} 類別設定應如何執行已排定的工作。您可以排定工作在特定條件下執行,例如:</p>
+
+<ul>
+ <li>當裝置充電時啟動</li>
+ <li>當裝置連線到非計量付費網路時啟動</li>
+ <li>當裝置閒置時啟動</li>
+ <li>在特定期限之前完成或稍微延遲後完成</li>
+</ul>
+
+<p>舉例來說,您可以新增下列程式碼,以便在非計量付費網路執行工作:</p>
+
+<pre>
+JobInfo uploadTask = new JobInfo.Builder(mJobId,
+ mServiceComponent /* JobService component */)
+ .setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED)
+ .build();
+JobScheduler jobScheduler =
+ (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
+jobScheduler.schedule(uploadTask);
+</pre>
+
+<p>如果裝置具備穩定的電力 (也就是裝置已接上電源超過 2 分鐘,而且電池處於<a href="{@docRoot}reference/android/content/Intent.html#ACTION_BATTERY_OKAY">健康狀態</a>),即使排定工作的期限還沒到,系統也會執行任何準備就緒的排定工作。</p>
+
+<p>如要查看 {@link android.app.job.JobScheduler} API 的使用示例,請參閱這個版本中的 {@code JobSchedulerSample} 實作示例。</p>
+
+<h3 id="PowerMeasurementTools">監控耗電量的開發人員工具</h3>
+
+<p>全新的 {@code dumpsys batterystats} 指令會產生值得您注意的裝置耗電量統計資料,並依照不重複使用者 ID (UID) 排列。統計資料包含:</p>
+
+<ul>
+<li>與電池相關的事件紀錄
+<li>裝置的一般統計資料
+<li>每個 UID 和系統元件的概略耗電量
+<li>每個封包的每個應用程式手機毫秒數
+<li>系統 UID 彙總統計資訊
+<li>應用程式 UID 彙總統計資訊
+</ul>
+
+<p>如要瞭解對輸出結果進行自訂的各種選項,請使用 {@code --help} 選項。例如,如要列出特定應用程式套件自裝置上次充電後的耗電量統計資訊,請執行下列指令:
+<pre>
+$ adb shell dumpsys batterystats --charged &lt;package-name&gt;
+</pre>
+
+<p>您可以對 {@code dumpsys} 指令的輸出使用 <a href="https://github.com/google/battery-historian" class="external-link">Battery Historian</a> 工具,利用紀錄中與電力相關的事件產生 HTML 圖示。這項資訊可讓您更輕鬆地掌握及診斷任何與電池相關的問題。</p>
+
+<h2 id="Enterprise">Android 在工作和教育方面的應用</h2>
+<h3 id="ManagedProvisioning">管理化設定檔建置</h3>
+
+<p>Android 5.0 提供了新功能,可讓您在企業環境內執行應用程式。如果使用者擁有現有的個人帳戶,則<a href="{@docRoot}guide/topics/admin/device-admin.html">裝置管理員</a>可以啟動管理化設定檔建置流程,將共存但獨立的「管理化設定檔」<em></em>新增到裝置中。與管理化設定檔相關聯的應用程式將與非管理化應用程式一起出現在使用者的啟動器、最近使用項目的螢幕以及通知中。</p>
+
+<p>如要啟動管理化設定檔建置流程,請在 {@link android.content.Intent} 中傳送 {@link android.app.admin.DevicePolicyManager#ACTION_PROVISION_MANAGED_PROFILE ACTION_PROVISION_MANAGED_PROFILE}。如果呼叫成功,系統將觸發 {@link android.app.admin.DeviceAdminReceiver#onProfileProvisioningComplete(android.content.Context, android.content.Intent) onProfileProvisioningComplete()} 回呼。然後,您就可以呼叫 {@link android.app.admin.DevicePolicyManager#setProfileEnabled(android.content.ComponentName) setProfileEnabled()} 以啟用這個管理化設定檔。</p>
+
+<p>在預設情況下,管理化設定檔中只會啟用一部分的應用程式。只要呼叫 {@link android.app.admin.DevicePolicyManager#enableSystemApp(android.content.ComponentName, android.content.Intent) enableSystemApp()},您就可以在受管理的設定檔安裝額外的應用程式。</p>
+
+<p>如果您在開發啟動器應用程式,不妨使用全新的 {@link android.content.pm.LauncherApps} 類別,取得目前使用者和任何關聯的受管理設定檔的可啟動活動清單。只要在可編輯的圖示上附加工作徽章,您的啟動器便能讓管理化應用程式變得更加顯目。如要擷取附帶徽章的圖示,請呼叫 {@link android.content.pm.PackageManager#getUserBadgedIcon(android.graphics.drawable.Drawable, android.os.UserHandle) getUserBadgedIcon()}。</p>
+
+<p>如要查看這項新功能的使用方式,請參閱這個版本的 {@code BasicManagedProfile} 實作示例。</p>
+
+<h3 id="DeviceOwner">裝置擁有者</h3>
+<p>Android 5.0 導入了部署裝置擁有者應用程式的功能。與一般<em></em><a href="{@docRoot}guide/topics/admin/device-admin.html">裝置管理員</a>不同,「裝置擁有者」另外具備在裝置上建立及移除次要使用者,以及配置全域設定的能力。您的裝置擁有者應用程式可以使用 {@link android.app.admin.DevicePolicyManager} 類別中的方法,針對受管理的裝置的設定、安全性和應用程式進行精細的控制。無論在任何時候,每部裝置都只能具備一個有效的裝置擁有者。</p>
+
+<p>如要部署並啟用裝置擁有者,您必須在裝置尚未進行設定建置時,先透過 NFC 將程式設計應用程式的資料傳輸到裝置中。這項資料傳輸作業所傳送的資訊,與<a href="#ManagedProvisioning">受管理的設定檔建置</a>中描述的建置調用請求所傳送的資訊相同。</p>
+
+<h3 id="ScreenPinning">螢幕固定</h3>
+
+<p>Android 5.0 導入了全新的螢幕固定 API,可讓您暫時防止使用者離開您的工作或受到通知干擾。舉例來說,如果您正在開發可在 Android 或單一用途或 Kiosk 應用程式上支援高風險評估需求的教育應用程式,則可以使用這個功能。您的應用程式啟用了螢幕固定之後,使用者將無法看到通知、存取其他應用程式或返回主畫面,直到您的應用程式退出這個模式為止。</p>
+
+<p>您可透過兩種方法啟用螢幕固定:</p>
+
+<ul>
+<li><strong>手動</strong>:使用者可以依序點選 [設定] &gt; [安全性] &gt; [螢幕固定]<em></em> 啟用螢幕固定。只要在最近使用項目的螢幕上點選綠色的螢幕固定圖示,然後選擇要固定的工作即可。</li> <li><strong>透過程式</strong>:如要透過程式啟用螢幕固定功能,請在您的應用程式中呼叫 {@link android.app.Activity#startLockTask() startLockTask()}。如果發出請求的應用程式不是裝置擁有者,系統會提示使用者進行確認。只要呼叫 {@link android.app.admin.DevicePolicyManager#setLockTaskPackages(android.content.ComponentName, java.lang.String[]) setLockTaskPackages()} 方法,裝置擁有者應用程式就可讓應用程式成為可固定的項目,完全不需要經過使用者確認。</li>
+</ul>
+
+<p>當工作鎖定處於有效狀態時,就會發生下列行為:</p>
+
+<ul>
+<li>狀態列空白,而且使用者通知和狀態資訊都會隱藏。</li>
+<li>「主畫面」和「最近使用的應用程式」按鈕都會隱藏。</li>
+<li>其他應用程式無法啟動新活動。</li>
+<li>目前的應用程式可以啟動新活動,只要這項動作不會建立新工作即可。</li>
+<li>如果螢幕固定是由裝置擁有者叫用,使用者將會保持鎖定在您的應用程式,直到應用程式呼叫 {@link android.app.Activity#stopLockTask() stopLockTask()} 為止。</li>
+<li>如果螢幕固定是由非裝置擁有者的應用程式或是由使用者直接呼叫的活動,使用者可以透過同時按住「返回」和「最近」按鈕退出。</li>
+
+</ul>
+
+<h2 id="Printing">列印架構</h2>
+
+<h3 id="PDFRender">將 PDF 轉譯為點陣圖</h3>
+<p>您現在可以使用新的 {@link android.graphics.pdf.PdfRenderer} 類別將 PDF 文件頁面轉譯為點陣圖圖片以便列印。您必須指定可尋找 (也就是內容可供隨機存取) 的 {@link android.os.ParcelFileDescriptor},方便系統將可列印內容寫入其中。您的應用程式可以透過 {@link android.graphics.pdf.PdfRenderer#openPage(int) openPage()} 取得頁面進行轉譯,然後再呼叫 {@link android.graphics.pdf.PdfRenderer.Page#render(android.graphics.Bitmap, android.graphics.Rect, android.graphics.Matrix, int) render()},將開啟的 {@link android.graphics.pdf.PdfRenderer.Page} 轉變為點陣圖。如果您只希望將文件的一部分轉變為點陣圖圖片 (例如,想要實作<a href="http://en.wikipedia.org/wiki/Tiled_rendering" class="external-link">圖塊轉譯</a>以放大文件),還可以設定其他參數。</p>
+
+<p>如需瞭解全新 API 的使用示例,請參閱 {@code PdfRendererBasic} 示例。</p>
+
+<h2 id="System">系統</h2>
+<h3 id="AppUsageStatistics">應用程式使用統計資料</h3>
+<p>透過全新的 {@link android.app.usage} API,您現在可以存取 Android 裝置上的應用程式使用紀錄。與已淘汰的 {@link android.app.ActivityManager#getRecentTasks(int, int) getRecentTasks()} 方法相比,這個 API 提供了更詳細的使用資訊。如要使用這個 API,您必須先在資訊清單中宣告 {@code "android.permission.PACKAGE_USAGE_STATS"} 權限。如要存取使用紀錄,使用者還必須依序點擊 [設定] &gt; [安全性] &gt; [應用程式]<em></em>,啟用對這個應用程式的存取權限。</p>
+
+<p>系統將以每個應用程式為單位收集使用資料,並依照每天、每週、每月和每年的時間間隔彙總資料。系統對於這些資料的最長保留期限分別為:</p>
+
+<ul>
+ <li>每日資料:7 天</li>
+ <li>每週資料:4 週</li>
+ <li>每月資料:6 個月</li>
+ <li>每年資料:2 年</li>
+</ul>
+
+<p>至於每個應用程式,系統會記錄下列資料:</p>
+<ul>
+<li>應用程式上次的使用時間</li>
+<li>應用程式在該時間間隔內 (依日、週、月或年排列) 處於前景的總時間長度</li>
+<li>元件 (以套件和活動名稱標識) 在一天中移動到前景或背景時擷取的時間戳記</li>
+<li>裝置設定變更時 (例如裝置設定因旋轉而變更時) 擷取的時間戳記</li>
+</ul>
+
+<h2 id="TestingA11y">測試和協助工具 </h2>
+
+<h3 id="TestingA11yImprovements">測試和協助工具改進部分</h3>
+<p>Android 5.0 新支援了下列測試和協助工具:</p>
+
+<ul>
+<li>全新的 {@link android.app.UiAutomation#getWindowAnimationFrameStats() getWindowAnimationFrameStats()} 和 {@link android.app.UiAutomation#getWindowContentFrameStats(int) getWindowContentFrameStats()} 方法會擷取視窗動畫和內容的影格統計資訊。這些方法可讓您編寫解析測試,以便評估應用程式轉譯影格的重新整理頻率是否足以提供流暢的使用者體驗。</li>
+
+<li>全新的 {@link android.app.UiAutomation#executeShellCommand(java.lang.String) executeShellCommand()} 方法可讓您透過解析測試執行殼層介面指令。指令執行作業與您從連接到裝置的主機執行 {@code adb shell} 的作業類似,但是可讓您使用殼層介面的工具,例如 {@code dumpsys}、{@code am} {@code content} 和 {@code pm}。</li>
+
+<li>對於視力正常的使用者在畫面上互動的視窗,現在只要使用協助工具 API (例如 <a href="{@docRoot}tools/help/uiautomator/index.html">{@code UiAutomator}</a>) 的協助工具服務和測試工具,即可擷取這些視窗的屬性詳細資訊。如要擷取 {@link android.view.accessibility.AccessibilityWindowInfo} 物件清單,請呼叫新的 {@link android.accessibilityservice.AccessibilityService#getWindows() getWindows()}·方法。</li>
+
+<li>全新 {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} 類別允許您定義可以對 {@link android.view.accessibility.AccessibilityNodeInfo} 執行的標準或自訂操作。全新 {@link android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction} 類別取代了以前在 {@link android.view.accessibility.AccessibilityNodeInfo} 中提供的操作相關 API。</li>
+
+<li>針對您應用程式中的文字轉語音合成功能,Android 5.0 提供了更細微的控制。全新 {@link android.speech.tts.Voice} 類別可讓您的應用程式使用與特定區域設定、品質和延遲等級相關聯的語音設定檔,以及文字轉語音引擎專屬的參數。</li>
+</ul>
+
+<h2 id="IME">IME</h2>
+
+<h3 id="Switching">切換輸入語言更輕鬆</h3>
+
+<p>從 Android 5.0 開始,使用者可以更輕鬆地在平台支援的所有<a href="{@docRoot}guide/topics/text/creating-input-method.html">輸入法編輯器 (IME) </a> 之間進行切換。當您執行指定的切換操作時 (通常是輕觸軟鍵盤上的地球圖示),將會依序看到所有 IME。這項行為變更是由 {@link android.view.inputmethod.InputMethodManager#shouldOfferSwitchingToNextInputMethod(android.os.IBinder) shouldOfferSwitchingToNextInputMethod()} 方法實作。</p>
+
+<p>此外,這個架構現在還會檢查下一個 IME 是否包含切換機制 (並同時確認這個 IME 是否支援切換到下一個 IME 的功能)。具備切換機制的 IME 不會切換到沒有切換機制的 IME。這項行為變更是由 {@link android.view.inputmethod.InputMethodManager#switchToNextInputMethod(android.os.IBinder, boolean) switchToNextInputMethod()} 方法實作。
+
+<p>如要查看更新版 IME 切換 API 的使用示例,請參閱這個版本中更新的軟鍵盤實作示例。如要進一步瞭解實作 IME 切換機制的方法,請參閱<a href="{@docRoot}guide/topics/text/creating-input-method.html">建立輸入法</a>。
+</p>
+
+<h2 id="Manifest">資訊清單宣告</h2>
+
+<h3 id="ManifestFeatures">可宣告的必要功能</h3>
+<p><a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> 元素現在支援下列各值,有助您確保應用程式只會安裝在提供應用程式所需功能的裝置上。</p>
+
+<ul>
+<li>{@link android.content.pm.PackageManager#FEATURE_AUDIO_OUTPUT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_POST_PROCESSING}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_MANUAL_SENSOR}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_CAPABILITY_RAW}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_CAMERA_LEVEL_FULL}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_GAMEPAD}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LIVE_TV}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_MANAGED_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_LEANBACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_OPENGLES_EXTENSION_PACK}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SECURELY_REMOVES_USERS}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_AMBIENT_TEMPERATURE}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_HEART_RATE_ECG}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_SENSOR_RELATIVE_HUMIDITY}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_VERIFIED_BOOT}</li>
+<li>{@link android.content.pm.PackageManager#FEATURE_WEBVIEW}</li>
+</ul>
+
+<h3 id="Permissions">使用者權限</h3>
+
+<p><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html">{@code <uses-permission>}</a> 元素現在支援下列權限,以便宣告您的應用程式存取特定 API 時所需的權限。</p>
+
+<ul>
+<li>{@link android.Manifest.permission#BIND_DREAM_SERVICE}:如果您的應用程式指定 API 等級 21 以上,<a href="{@docRoot}about/versions/android-4.2.html#Daydream">Daydream</a> 服務需要這項權限,以確保只有系統可以建立繫結。</li>
+</ul>
diff --git a/docs/html-intl/intl/zh-tw/about/versions/lollipop.jd b/docs/html-intl/intl/zh-tw/about/versions/lollipop.jd
new file mode 100644
index 0000000..d05e5db
--- /dev/null
+++ b/docs/html-intl/intl/zh-tw/about/versions/lollipop.jd
@@ -0,0 +1,254 @@
+page.title=Android Lollipop
+
+@jd:body
+
+
+
+
+
+
+
+
+
+
+ <div style="padding:0px 0px 0px 20px;float:right;margin:0 -10px 0 0">
+ <img src="{@docRoot}images/home/l-hero_2x.png" srcset="{@docRoot}images/home/l-hero.png 1x, {@docRoot}images/home/l-hero_2x.png 2x" width="460" height="300" >
+ </div>
+
+ <div class="landing-docs" style="float:right;clear:both;margin:68px 0 2em 3em;">
+ <div class="col-4 normal-links highlights" style="font-size:12px;">
+ <h3 id="thisd" >主要開發人員功能</h3>
+ <ul style="list-style-type:none;">
+ <li><a href="#Material">實感設計</a></li>
+ <li><a href="#Perf">聚焦優異效能</a></li>
+ <li><a href="#Notifications">通知</a></li>
+ <li><a href="#TV">您的應用程式躍上大螢幕</a></li>
+ <li><a href="#Documents">文件導向的應用程式</a></li>
+ <li><a href="#Connectivity">進階連線功能</a></li>
+ <li><a href="#Graphics">高效能圖形運算機制</a></li>
+ <li><a href="#Audio">更強大的音訊功能</a></li>
+ <li><a href="#Camera">改良的相機功能和視訊處理能力</a></li>
+ <li><a href="#Work">Android 在工作方面的應用</a></li>
+ <li><a href="#ScreenCapture">螢幕擷取和分享</a></li>
+ <li><a href="#Sensors">全新的感應器類型</a></li>
+ <li><a href="#WebView">Chromium WebView</a></li>
+ <li><a href="#Accessibility">協助工具和輸入功能</a></li>
+ <li><a href="#Battery">用於打造低耗電應用程式的工具</a></li>
+ </ul>
+ </div>
+</div>
+
+
+
+
+
+
+
+<p>歡迎使用 Android 5.0 Lollipop,這是目前為止規模最大、功能最強的 Android 版本!</p>
+
+<p>這個版本不僅為使用者提供了許多新功能,也為開發人員提供了數以千計的全新 API。Android 的應用領域也因此從手機、平板電腦、穿戴式裝置,進一步擴展到電視和汽車。</p>
+
+<p>如要深入瞭解全新的開發人員 API,請參閱 <a href="{@docRoot}about/versions/android-5.0.html">Android 5.0 API 總覽</a>。如需適合一般消費者閱讀的 Android 5.0 相關資訊,請前往 <a href="http://www.android.com/versions/lollipop-5-0/">www.android.com</a>。</p>
+
+<h2 id="Material">實感設計</h2>
+
+<p>Android 5.0 將<a href="http://www.google.com/design/spec">實感設計</a>功能 (Material Design) 導入到 Android 中,並為您提供了更加完善的使用者介面工具套件,讓您輕鬆將全新的設計模式整合到應用程式中。 </p>
+
+
+
+<p>全新 <strong>3D 檢視模式</strong>可讓您設定 z-level,讓元素高過檢視階層並投射<strong>即時陰影</strong>,即使元素移動時也沒問題。</p>
+
+
+<p>透過內建<strong>活動轉換效果</strong>的優美動畫,帶領使用者體驗流暢的狀態切換畫面。實感主題可為您的活動新增轉換效果,包括在各個活動中使用<strong>共用視覺化元素</strong>的功能。</p>
+
+
+
+<div style="width:290px;margin-right:35px;float:left">
+ <div class="framed-nexus5-port-span-5">
+ <video class="play-on-hover" autoplay="">
+ <source src="/design/material/videos/ContactsAnim.mp4">
+ <source src="/design/videos/ContactsAnim.webm">
+ <source src="/design/videos/ContactsAnim.ogv">
+ </video>
+ </div>
+ <div style="font-size:10pt;margin-left:20px;margin-bottom:30px">
+ 如要播放影片,請按一下裝置螢幕<em></em>
+ </div>
+</div>
+
+
+<p>您可以為按鈕、核取方塊和應用程式中的其他觸控控制項套用波紋動畫。
+
+<p>您也能以 XML 定義向量圖形可繪項目,並透過多種方式套用動畫效果。向量圖形可繪項目縮放時不會失真,因此最適合用於應用程式內的單色圖示。</p>
+
+<p><strong>RenderThread</strong> 是全新的系統管理執行緒,即使主要使用者介面執行緒中發生延遲,仍可確保動畫流暢播放。 </p>
+
+
+<h2 id="Perf">效能導向</h2>
+
+<p>Android 5.0 為您提供更快、更流暢且更強大的運算體驗。</p>
+
+<p>Android 現在只會在全新 <strong>ART Runtime</strong> 上執行。ART 完全從零打造,可混合支援預先 (AOT) 編譯、準時 (JIT) 編譯和直譯程式碼。ART 受到 ARM、x86 和 MIPS 架構支援 ,並且完全與 64 位元相容。</p>
+
+<p>ART 可提升應用程式的效能和回應靈敏度。有效率的垃圾資訊收集作業可減少垃圾收集事件的暫停次數和持續時間。正因為垂直同步時段內的垃圾資訊收集事件,您的應用程式才不會忽略影格。如果需要在前景使用,ART 還會動態移動記憶體將效能最佳化。 </p>
+
+<p>Android 5.0 導入了對 <strong>64 位元架構</strong>的平台支援 (Nexus 9 的 NVIDIA Tegra K1 使用該架構)。針對特定的運算工作負載,最佳化作業可提供更大的位址空間和改進的效能。以 Java 語言編寫的應用程式可自動做為 64 位元應用程式執行,完全不需要任何修改。如果您的應用程式使用原生程式碼,請注意我們已擴展 NDK,現在可支援適用於 ARM v8、x86-64 和 MIPS-64 的全新 ABI。</p>
+
+<p>延續對於流暢效能的重視,Android 5.0 提供了改進的音訊/視訊同步功能。我們已校準音訊和圖形管道,可以提供更準確的時間戳記,讓影片應用程式和遊戲顯示流暢同步的影音內容。</p>
+
+
+<h2 id="Notifications">通知</h2>
+
+<p>在 Android 5.0 中,通知變得更明顯可見、更容易存取,同時也更容易設定。 </p>
+
+<img src="{@docRoot}images/versions/notification-headsup.png" style="float:right; margin:0 0 40px 60px" width="300" height="224" />
+
+<p>對於<strong>鎖定畫面上</strong>所顯示的通知詳細資訊,使用者可以視需要自行調整。使用者可選擇在安全的鎖定畫面上不顯示任何內容、顯示部分內容,或者顯示所有內容。 </p>
+
+<p>重要的通知提醒 (例如來電) 將顯示在<strong>提醒通知</strong>中。提醒通知是一個小型的浮動視窗,使用者不需要離開目前的應用程式即可回應或關閉提醒通知。</p>
+
+<p>您現在可以在通知中新增<strong>全新中繼資料</strong>,以便收集相關聯的聯絡人 (用於排名)、類別和優先級。</p>
+
+<p>此外,我們也提供了全新的媒體通知範本,目的是讓通知的媒體控制項保持一致,最多不超過 6 個操作按鈕 (包括「豎起拇指」之類的自訂控制項),從此再也不需要 RemoteViews!</p>
+
+
+
+<h2 id="TV">您的應用程式躍上大螢幕</h2>
+
+<p><a href="http://developer.android.com/tv/index.html">Android TV</a> 提供了完整的電視平台,讓您的應用程式輕鬆躍上大螢幕。Android TV 的設計概念就是圍繞著簡化的主螢幕體驗向外延伸,讓使用者透過量身打造的推薦和語音搜尋,輕鬆發掘新奇內容。</p>
+
+<p>透過 Android TV,您現在不但可以為應用程式或遊戲內容<strong>營造寬廣且鮮明的體驗</strong>,還可以支援與遊戲控制器和其他輸入裝置進行互動的功能。為協助您針對電視打造擁有劇院級效果且在 7 公尺外依然清晰可見的使用者介面,Android 在 <a href="{@docRoot}tools/support-library/features.html#v17-leanback">v17 支援程式庫</a>中提供了一個 <strong>Leanback 使用者介面架構</strong>。</p>
+
+<p><strong>Android TV 輸入架構</strong> (TIF) 允許電視應用程式處理 HDMI 輸入端、電視協調器、IPTV 接收器等來源的影片串流。透過 TV 輸入架構發佈的中繼資料,還可提供直播電視搜尋和推薦功能,並且包括一項 HDMI-CEC 控制服務,可讓使用者透過一個遙控器操控多個裝置。 </p>
+
+<p>TV 輸入架構可存取廣泛的直播電視輸入來源,並將它們彙集在單一使用者介面中,讓使用者瀏覽、查看及觀賞精彩內容。如果希望您的內容更容易在電視裝置上使用,不妨為您的內容建構電視輸入服務。</p>
+
+
+
+<img src="{@docRoot}images/versions/recents_screen_2x.png" srcset="{@docRoot}images/versions/recents_screen.png 1x, {@docRoot}images/versions/recents_screen_2x.png 2x" style="float:right; margin:0 0 40px 60px" width="300" height="521" />
+
+<h2 id="Documents">文件導向的應用程式</h2>
+
+<p>Android 5.0 導入了重新設計的「概覽」空間 (之前稱為「最近使用的項目」),用途更廣而且非常適合多工作業。</p>
+
+<p>透過全新的 API,您可將應用程式中的活動當做獨立的文件,與其他最近使用項目的螢幕一起顯示。</p>
+
+<p>您可以運用同時顯示多份文件的功能,讓使用者即時存取更多內容或服務。例如,您可以運用同時顯示多份文件的功能,呈現生產力應用程式中的檔案、遊戲中的玩家比賽,或者是即時通訊應用程式中的通訊內容。 </p>
+
+
+
+<h2 id="Connectivity">進階連線功能</h2>
+
+<p>Android 5.0 增加了全新 API,可讓應用程式透過<strong>藍牙低功耗技術</strong> (BLE) 執行並行操作,因此可同時掃描 (中央模式) 和廣告 (週邊模式)。</p>
+
+<p>透過全新的<strong>多網路</strong>功能,應用程式可查詢具備特定功能的可用網路,例如 Wi-Fi 網路、行動數據網路或是按傳輸量計費網路,以及這些網路是否提供了特定的網路功能。之後,應用程式就可以要求連線,並對連線中斷或其他網路變動做出回應。</p>
+
+<p><strong>NFC</strong> API 現在不但可讓應用程式動態註冊 NFC 應用程式 ID (AID),還可根據目前為有效狀態的服務設定偏好的卡片模擬服務,並且建立包含 UTF-8 文字資料的 NDEF 紀錄。</p>
+
+
+
+<h2 id="Graphics">高效能圖形運算機制</h2>
+
+<p>在受支援的裝置上,<strong><a href="http://www.khronos.org/opengles/3_X/">Khronos OpenGL ES 3.1</a></strong> 現在可為遊戲和其他應用程式提供最高效能的 2D 和 3D 圖形功能。 </p>
+
+<p>OpenGL ES 3.1 新增了運算著色器、型染紋理、加速的視覺效果、高品質 ETC2/EAC 紋理壓縮、進階紋理轉譯、標準化紋理大小和轉譯緩衝區格式等功能。</p>
+
+
+<div class="figure" style="width:350px; margin:0 0 0 60px">
+<img src="{@docRoot}images/versions/rivalknights.png" style="float:right;" width="350" height="525" />
+<p class="img-caption">Gameloft 開發的《決鬥騎士》採用 AEP 的 ASTC (自動調整可縮放紋理壓縮) 和 ES 3.1 中的運算著色器,完美呈現了 HDR (高動態範圍) 泛光效果和更多圖形細節。</p>
+</div>
+
+<p>此外,Android 5.0 也導入了 <strong>Android 擴充功能套件</strong> (AEP)。這組 OpenGL ES 擴充功能可讓您存取下列功能:曲面細分著色器、幾何圖形著色器、ASTC 紋理壓縮、取樣差補和著色,以及其他進階轉譯功能。有了 AEP,您的應用程式便能支援多種 GPU,有效提高圖形運算效率。</p>
+
+
+<h2 id="Audio">更強大的音訊功能</h2>
+
+<p>全新的音訊擷取設計提供了<strong>低延遲音訊輸入</strong>功能。這項新設計包括:永遠不會被封鎖的快速擷取執行緒 (讀取期間除外);採用原生採樣速率、聲道數量和位元深度的快速擷取用戶端;以及可提供重新採樣、上/下聲道混合以及上/下位元深度的一般擷取用戶端。</p>
+
+<p>多聲道<strong>音訊串流混音</strong>可讓專業的音訊應用程式混合多達八個聲道,包括 5.1 和 7.1 聲道在內。</p>
+
+<p>應用程式現在可以公開媒體內容,並可<strong>瀏覽其他應用程式的媒體</strong>,然後請求播放。由於內容是透過具有查詢功能的介面公開,因此不需要存在於裝置上。</p>
+
+<p>透過與特定地區設定、品質和延遲等級相關聯的語音設定檔,應用程式可以精確掌控<strong>文字轉語音合成</strong>功能。新的 API 同時提升了對合成錯誤檢查、網路合成、語言搜尋和網路替代的支援能力。</p>
+
+<p>Android 現在包括對標準 <strong>USB 音訊</strong>週邊裝置的支援,可讓使用者連接 USB 耳機、喇叭、麥克風和其他高效能數位週邊裝置。Android 5.0 還增加了對 <strong>Opus</strong> 音訊轉碼器的支援。</p>
+
+<p>用於控制媒體播放功能的全新 <strong>{@link android.media.session.MediaSession}</strong> API,現在可讓您輕鬆在不同的螢幕和其他控制器之間提供一致的媒體控制項。</p>
+
+
+<h2 id="Camera">改良的相機和影片 &gt;&gt; </h2>
+
+<p>Android 5.0 導入了<strong>全新的相機 API</strong>,可讓您擷取原始格式 (例如 YUV 和 Bayer RAW),並以影格為單位對參數 (例如曝光時間、ISO 感光度和影格持續時間) 進行控制。透過全新的完全同步相機管道,您可在受支援的裝置上以每秒 30 影格的速率擷取未壓縮的全解析度 YUV 圖片。</p>
+
+<p>除了圖片之外,您還可透過相機擷取雜訊模型和光學資訊等中繼資料。</p>
+
+<p>透過網路傳送影片串流的應用程式現在可以利用 H.265 <strong>高效率影片編碼 (HEVC)</strong>,獲得影片資料的最佳編碼和解碼效能。 </p>
+
+<p>Android 5.0 也新增對<strong>多媒體隧道服務</strong>的支援,以便針對超高解析度 (4K) 內容提供最佳體驗,並能將壓縮的音訊和影片資料一起播放。 </p>
+
+
+
+<div class="figure" style="width:320px; margin:1em 0 0 20px;padding-left:2em;">
+<img style="float:right; margin:0 1em 1em 2em" src="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png" srcset="{@docRoot}images/android-5.0/managed_apps_launcher@2x.png 2x" alt="" width="300" />
+<p class="img-caption">使用者的個人應用程式和工作應用程式都會顯示在同一個檢視畫面。工作應用程式都附有徽章,方便您輕鬆識別。</p>
+</div>
+
+
+<h2 id="Work">Android 在工作方面的應用</h2>
+
+<p>為了在企業環境中實現「帶自己的行動裝置來上班」運動,我們新增了<a href="{@docRoot}about/versions/android-5.0.html#Enterprise">受管理的設定檔建置程序</a>,可在裝置上建立安全的工作設定檔。在啟動器中,如果應用程式附帶「工作」徽章,表示該應用程式和資料是由 IT 管理員在工作設定檔內管理的。</p>
+
+<p>個人設定檔和工作設定檔的通知都會顯示在同一個檢視畫面。每個設定檔的資料彼此獨立,安全無虞。即使兩個設定檔使用同一個應用程式,也不會造成安全上的顧慮。</p>
+
+<p>對於公司擁有的裝置,IT 管理員可以著手處理新裝置並為其設定<a href="{@docRoot}about/versions/android-5.0.html#DeviceOwner">裝置擁有者</a>。完成後,雇主就可以發放已安裝裝置擁有者應用程式的裝置,而這些裝置都可以設置全域的裝置設定。</p>
+
+
+
+<h2 id="ScreenCapture">螢幕擷取和分享</h2>
+
+<p>Android 5.0 可讓您在應用程式中新增螢幕擷取和分享功能。 </p>
+
+<p>如果具有相關使用者權限,您就可以擷取螢幕上未設定安全防護的影片,並視需要選擇透過網路傳送。</p>
+
+
+<h2 id="Sensors">全新的感應器類型</h2>
+
+<p>在 Android 5.0 中,全新的<strong>傾斜偵測</strong>感應器可有效提升受支援裝置上的活動識別準確度,<strong>心率感應器</strong>則可回報觸摸裝置的使用者目前的心跳速率。 </p>
+
+<p>全新的<strong>互動複合感應器</strong>現在可用來偵測特殊互動,例如「喚醒」<em></em>手勢、<em></em>「拿取」手勢和<em></em>「掃視」手勢。</p>
+
+
+
+<h2 id="WebView">Chromium WebView</h2>
+
+<div style="float:right;margin:1em 2em 1em 2em;">
+ <img src="/images/kk-chromium-icon.png" alt="" height="160" style="margin-bottom:0em;">
+</div>
+
+<p>Android 5.0 最初版本包含以 Chromium M37 版為基礎的 Chromium for {@link android.webkit.WebView},藉此增加了 <strong>WebRTC</strong>、<strong>WebAudio</strong> 和 <strong>WebGL</strong> 支援功能。 </p>
+
+<p>Chromium M37 也包含對於所有 <strong>Web Components</strong> 規格 (例如 Custom Elements、Shadow DOM、HTML Imports 和 Templates) 的原生支援。這表示您不需要 Polyfill,即可在 WebView 中使用 <a href="http://polymer-project.org/">Polymer</a> 和相關的<a href="https://www.polymer-project.org/docs/elements/material.html">實感設計元素</a>。</p>
+
+<p>雖然自 Android 4.4 以來,WebView 都是以 Chromium 為基礎,但您現在可以從 Google Play 更新 Chromium 層。</p>
+
+<p>Chromium 新版本推出時,使用者便可以透過 Google Play 進行更新,讓 WebView 能夠取得最新的增強功能,並修正相關錯誤。這表示開發人員能夠讓使用 WebView 的應用程式 (Android 5.0 版以上) 取得最新的 Web API,同時修正各項錯誤。</p>
+
+
+
+<h2 id="Accessibility">協助工具和輸入功能</h2>
+
+<p>對於視力正常的使用者在畫面上互動的視窗,現在只要使用全新的協助工具 API,即可擷取這些視窗的屬性詳細資訊。全新的協助工具 API 也可為使用者介面元素定義標準或自訂的輸入操作。</p>
+
+<p>透過全新輸入法編輯器 (IME) API,使用者可以直接從目前的輸入法迅速切換到其他 IME。</p>
+
+
+
+<h2 id="Battery">用於打造低耗電應用程式的工具</h2>
+
+<p>全新的<strong>排定工作</strong> API 可讓您為系統定義延後執行的工作或是在特定條件下 (例如裝置充電或連接到 Wi-Fi 時) 執行的工作,進而將電池電力最佳化。</p>
+
+<p>全新的 <code>dumpsys batterystats</code> 指令會產生<strong>耗電量統計資料</strong>,您可以使用這項統計資料瞭解整個系統的用電情況,並掌握您的應用程式對裝置電池的影響。您可以查看電力事件、每個 UID 和系統元件的大致用電量等紀錄資訊。</p>
+
+<img src="{@docRoot}images/versions/battery_historian.png" srcset="{@docRoot}images/versions/battery_historian@2x.png 2x" alt="" width="760" height="462" />
+<p class="img-caption">Battery Historian 這項新工具可以將 <code>dumpsys batterystats</code> 的統計資料轉換為圖示,以便進行與電力相關的偵錯作業。您可以在 <a href="https://github.com/google/battery-historian">https://github.com/google/battery-historian</a> 找到這項工具。</p>
diff --git a/docs/html/about/about_toc.cs b/docs/html/about/about_toc.cs
index 9033d69..b1357f2 100644
--- a/docs/html/about/about_toc.cs
+++ b/docs/html/about/about_toc.cs
@@ -7,11 +7,26 @@
</ul>
</li>
<li class="nav-section">
- <div class="nav-section-header"><a href="<?cs var:toroot ?>about/versions/lollipop.html">
+ <div class="nav-section-header"><a href="<?cs var:toroot ?>about/versions/lollipop.html"
+ zh-tw-lang="Lollipop"
+ zh-cn-lang="Lollipop"
+ ru-lang="Lollipop"
+ ko-lang="Lollipop"
+ ja-lang="Lollipop"
+ es-lang="Lollipop">
<span class="en">Lollipop</span></a></div>
<ul>
- <li><a href="<?cs var:toroot ?>about/versions/android-5.0.html">Android 5.0 APIs</a></li>
- <li><a href="<?cs var:toroot ?>about/versions/android-5.0-changes.html">Android 5.0 Changes</a></li>
+ <li><a href="<?cs var:toroot ?>about/versions/android-5.0.html"
+ zh-tw-lang="Android 5.0 API"
+ zh-cn-lang="Android 5.0 API"
+ ru-lang="API для Android 5.0"
+ ko-lang="Android 5.0 API"
+ ja-lang="Android 5.0 API"
+ es-lang="API de Android 5.0">
+ Android 5.0 APIs</a></li>
+ <li><a href="<?cs var:toroot ?>about/versions/android-5.0-changes.html">
+
+ Android 5.0 Changes</a></li>
</ul>
</li>
<li class="nav-section">
diff --git a/docs/html/about/dashboards/index.jd b/docs/html/about/dashboards/index.jd
index 5265f20..4e03108 100644
--- a/docs/html/about/dashboards/index.jd
+++ b/docs/html/about/dashboards/index.jd
@@ -57,7 +57,7 @@ Platform Versions</a>.</p>
</div>
-<p style="clear:both"><em>Data collected during a 7-day period ending on January 5, 2015.
+<p style="clear:both"><em>Data collected during a 7-day period ending on February 2, 2015.
<br/>Any versions with less than 0.1% distribution are not shown.</em>
</p>
@@ -88,7 +88,7 @@ Screens</a>.</p>
</div>
-<p style="clear:both"><em>Data collected during a 7-day period ending on January 5, 2015.
+<p style="clear:both"><em>Data collected during a 7-day period ending on February 2, 2015.
<br/>Any screen configurations with less than 0.1% distribution are not shown.</em></p>
@@ -108,7 +108,7 @@ support for any lower version (for example, support for version 2.0 also implies
<img alt="" style="float:right"
-src="//chart.googleapis.com/chart?chl=GL%202.0%7CGL%203.0&chf=bg%2Cs%2C00000000&chd=t%3A69.9%2C30.1&chco=c4df9b%2C6fad0c&cht=p&chs=400x250" />
+src="//chart.googleapis.com/chart?chl=GL%202.0%7CGL%203.0&chf=bg%2Cs%2C00000000&chd=t%3A68.9%2C31.1&chco=c4df9b%2C6fad0c&cht=p&chs=400x250" />
<p>To declare which version of OpenGL ES your application requires, you should use the {@code
@@ -127,17 +127,17 @@ uses.</p>
</tr>
<tr>
<td>2.0</td>
-<td>69.9%</td>
+<td>68.9%</td>
</tr>
<tr>
<td>3.0</td>
-<td>30.1%</td>
+<td>31.1%</td>
</tr>
</table>
-<p style="clear:both"><em>Data collected during a 7-day period ending on January 5, 2015</em></p>
+<p style="clear:both"><em>Data collected during a 7-day period ending on February 2, 2015</em></p>
@@ -155,7 +155,7 @@ uses.</p>
var VERSION_DATA =
[
{
- "chart": "//chart.googleapis.com/chart?cht=p&chs=500x250&chco=c4df9b%2C6fad0c&chd=t%3A0.4%2C7.8%2C6.7%2C46.0%2C39.1&chf=bg%2Cs%2C00000000&chl=Froyo%7CGingerbread%7CIce%20Cream%20Sandwich%7CJelly%20Bean%7CKitKat",
+ "chart": "//chart.googleapis.com/chart?chf=bg%2Cs%2C00000000&chd=t%3A0.4%2C7.4%2C6.4%2C44.5%2C39.7%2C1.6&chco=c4df9b%2C6fad0c&chl=Froyo%7CGingerbread%7CIce%20Cream%20Sandwich%7CJelly%20Bean%7CKitKat%7CLollipop&chs=500x250&cht=p",
"data": [
{
"api": 8,
@@ -165,32 +165,37 @@ var VERSION_DATA =
{
"api": 10,
"name": "Gingerbread",
- "perc": "7.8"
+ "perc": "7.4"
},
{
"api": 15,
"name": "Ice Cream Sandwich",
- "perc": "6.7"
+ "perc": "6.4"
},
{
"api": 16,
"name": "Jelly Bean",
- "perc": "19.2"
+ "perc": "18.4"
},
{
"api": 17,
"name": "Jelly Bean",
- "perc": "20.3"
+ "perc": "19.8"
},
{
"api": 18,
"name": "Jelly Bean",
- "perc": "6.5"
+ "perc": "6.3"
},
{
"api": 19,
"name": "KitKat",
- "perc": "39.1"
+ "perc": "39.7"
+ },
+ {
+ "api": 21,
+ "name": "Lollipop",
+ "perc": "1.6"
}
]
}
@@ -203,29 +208,29 @@ var SCREEN_DATA =
"data": {
"Large": {
"hdpi": "0.6",
- "ldpi": "0.6",
- "mdpi": "5.4",
- "tvdpi": "2.3",
+ "ldpi": "0.5",
+ "mdpi": "5.1",
+ "tvdpi": "2.2",
"xhdpi": "0.6"
},
"Normal": {
- "hdpi": "37.5",
- "mdpi": "8.8",
+ "hdpi": "38.3",
+ "mdpi": "8.7",
"tvdpi": "0.1",
- "xhdpi": "18.4",
- "xxhdpi": "16.3"
+ "xhdpi": "18.8",
+ "xxhdpi": "15.9"
},
"Small": {
"ldpi": "4.8"
},
"Xlarge": {
"hdpi": "0.3",
- "mdpi": "3.7",
+ "mdpi": "3.5",
"xhdpi": "0.6"
}
},
- "densitychart": "//chart.googleapis.com/chart?cht=p&chs=400x250&chco=c4df9b%2C6fad0c&chd=t%3A5.4%2C17.9%2C2.4%2C38.4%2C19.6%2C16.3&chf=bg%2Cs%2C00000000&chl=ldpi%7Cmdpi%7Ctvdpi%7Chdpi%7Cxhdpi%7Cxxhdpi",
- "layoutchart": "//chart.googleapis.com/chart?cht=p&chs=400x250&chco=c4df9b%2C6fad0c&chd=t%3A4.6%2C9.5%2C81.1%2C4.8&chf=bg%2Cs%2C00000000&chl=Xlarge%7CLarge%7CNormal%7CSmall"
+ "densitychart": "//chart.googleapis.com/chart?chf=bg%2Cs%2C00000000&chd=t%3A5.3%2C17.3%2C2.3%2C39.2%2C20.0%2C15.9&chco=c4df9b%2C6fad0c&chl=ldpi%7Cmdpi%7Ctvdpi%7Chdpi%7Cxhdpi%7Cxxhdpi&chs=400x250&cht=p",
+ "layoutchart": "//chart.googleapis.com/chart?chf=bg%2Cs%2C00000000&chd=t%3A4.4%2C9.0%2C81.8%2C4.8&chco=c4df9b%2C6fad0c&chl=Xlarge%7CLarge%7CNormal%7CSmall&chs=400x250&cht=p"
}
];
@@ -305,7 +310,7 @@ var VERSION_NAMES =
},
{
"api":21,
- "link":"<a href='/about/versions/android-5.0.html'>4.4</a>",
+ "link":"<a href='/about/versions/android-5.0.html'>5.0</a>",
"codename":"Lollipop"
}
];
diff --git a/docs/html/about/versions/android-5.0-changes.jd b/docs/html/about/versions/android-5.0-changes.jd
index 3de5c3c..f51af40 100644
--- a/docs/html/about/versions/android-5.0-changes.jd
+++ b/docs/html/about/versions/android-5.0-changes.jd
@@ -24,13 +24,6 @@ sdk.platform.apiLevel=21
<li><a href="#managed_profiles">Support for Managed Profiles</a></li>
</ol>
-<a class="notice-developers-video" href="https://www.youtube.com/watch?v=Uiq2kZ2JHVY">
-<div>
- <h3>Video</h3>
- <p>Notifications</p>
-</div>
-</a>
-
<h2>API Differences</h2>
<ol>
<li><a href="{@docRoot}sdk/api_diff/21/changes.html">API level 20 to 21 &raquo;</a> </li>
@@ -48,6 +41,20 @@ sdk.platform.apiLevel=21
</div>
</div>
+<a class="notice-developers-video" href="https://www.youtube.com/watch?v=um1S2u022HA">
+<div>
+ <h3>Video</h3>
+ <p>Dev Byte: What's New in Android 5.0</p>
+</div>
+</a>
+
+<a class="notice-developers-video" href="https://www.youtube.com/watch?v=Uiq2kZ2JHVY">
+<div>
+ <h3>Video</h3>
+ <p>Dev Byte: Notifications</p>
+</div>
+</a>
+
<p>API Level: {@sdkPlatformApiLevel}</p>
<p>Along with new features and capabilities, Android 5.0 includes a variety of
system changes and API behavior changes. This document highlights
diff --git a/docs/html/design/style/iconography.jd b/docs/html/design/style/iconography.jd
index d212b06..1a92753 100644
--- a/docs/html/design/style/iconography.jd
+++ b/docs/html/design/style/iconography.jd
@@ -516,23 +516,41 @@ application: </p>
<em>finished_asset</em>.png
drawable-xxhdpi/...
<em>finished_asset</em>.png
+
+ mipmap-ldpi/...
+ <em>finished_launcher_asset</em>.png
+ mipmap-mdpi/...
+ <em>finished_launcher_asset</em>.png
+ mipmap-hdpi/...
+ <em>finished_launcher_asset</em>.png
+ mipmap-xhdpi/...
+ <em>finished_launcher_asset</em>.png
+ mipmap-xxhdpi/...
+ <em>finished_launcher_asset</em>.png
+ mipmap-xxxhdpi/...
+ <em>finished_launcher_asset</em>.png
</pre>
<p>For more information about how to save resources in the application project,
see <a href="{@docRoot}guide/topics/resources/providing-resources.html">Providing Resources</a>.
</p>
+<p> For more information about using the mipmap folders, see
+<a href="{@docRoot}tools/project/index.html#mipmap">Managing Projects Overview</a>.</p>
<h3 id="xxxhdpi-launcher">Provide an xxx-high-density launcher icon</h3>
-<p>Some devices scale-up the launcher icon by as much as 25%. For example, if your highest density
+<p>Some devices scale-up the launcher icon by as much as 25%. For example, if your highest density
launcher icon image is already extra-extra-high density, the scaling process will make it appear
-less crisp. So you should provide a higher density launcher icon in the <code>drawable-xxxhdpi
+less crisp. So you should provide a higher density launcher icon in the <code>mipmap-xxxhdpi
</code> directory, which the system uses instead of scaling up a smaller version of the icon.</p>
-<p class="note"><strong>Note:</strong> the <code>drawable-xxxhdpi</code> qualifier is necessary only
-to provide a launcher icon that can appear larger than usual on an xxhdpi device. You do not need to
-provide xxxhdpi assets for all your app's images.</p>
+<p class="note"><strong>Note:</strong> The <code>mipmap-xxxhdpi</code> qualifier is necessary
+only to provide a launcher icon that can appear larger than usual on an xxhdpi device. It is best
+practice to place all your launcher icons in the <code>res/mipmap-[density]/</code> folders. This
+enables your app to display launcher icons that have a higher density than the device, without
+scaling up a lower density version of the icon. You do not need to provide xxxhdpi assets for all
+your app's images.</p>
<p>See <a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple Screens</a> for
more information.</p>
diff --git a/docs/html/design/wear/watchfaces.jd b/docs/html/design/wear/watchfaces.jd
index 99dc3dd..2a00802 100644
--- a/docs/html/design/wear/watchfaces.jd
+++ b/docs/html/design/wear/watchfaces.jd
@@ -101,7 +101,7 @@ format.</p>
<!-- H2: plan for all display modes -->
<div style="float:right;margin-top:35px;margin-left:20px">
<img src="{@docRoot}design/media/wear/Render_Interactive.png"
- width="200" height="195" alt="" style="margin-right:5px"/><br/>
+ width="200" height="195" alt="" style="margin-right:5px;margin-top:20px"/><br/>
<img src="{@docRoot}design/media/wear/Render_Ambient.png"
width="200" height="195" alt="" style="margin-right:5px"/>
</div>
@@ -118,11 +118,12 @@ mode. Your design can use full color with fluid animation in this mode.</p>
<h3>Ambient mode</h3>
<p>Ambient mode helps the device conserve power. Your design should make clear to the user that
-the screen is in ambient mode by using only grayscale colors. Do not use a lot of white in ambient
-mode, since this distracting and hurts battery life on some screens. In this mode, the screen
-is only updated once every minute. Only show hours and minutes in ambient mode; do not show
-seconds. Your watch face is notified when the device switches to ambient mode, and you should
-thoughtfully design for it.</p>
+the screen is in ambient mode. The background color scheme is <em>strictly limited</em> to black,
+white, and grays. Your watch face may use some color elements on screens that support it
+provided it is unambiguous that the device is in ambient mode. You can use color elements for up
+to 5 percent of total pixels. In this mode, the screen is only updated once every minute. Only
+show hours and minutes in ambient mode; do not show seconds. Your watch face is notified when
+the device switches to ambient mode, and you should thoughtfully design for it.</p>
@@ -131,23 +132,29 @@ thoughtfully design for it.</p>
<p>Android Wear devices feature a variety of screen technologies, each with their own advantages
and considerations. One important consideration when designing the ambient mode display for your
-watch face is how it affects battery life and screen burn-in on some screens.</p>
-
-<p>You can configure your watch face to display different ambient designs depending on the kind
+watch face is how it affects battery life and screen burn-in on some screens.
+You can configure your watch face to display different ambient designs depending on the kind
of screen available on the device. Consider the best design for your watch faces on all
screens.</p>
<div class="layout-content-row" style="margin-top:20px">
<div class="layout-content-col span-9">
- <h3>Low bit</h3>
- <p>Pixels on some screens (including OLED and transflective LED) in ambient mode are either
- "on" or "off", also known as "low-bit". When designing for low-bit ambient mode, use only black
- and white, avoid grayscale colors, and disable antialiasing in your paint styles. Make sure to
- test your design on devices with low-bit ambient mode.</p>
+ <h3>Reduced color space</h3>
+ <p>Some displays use a reduced color space in ambient mode to save power.</p>
+ <p>One reduced color space power saving method is to use a "low-bit" mode. In low-bit mode,
+ the available colors are limited to black, white, blue, red, magenta, green, cyan, and yellow.
+ When designing for low-bit ambient mode, use a black or a white background. For OLED screens,
+ you must use a black background. Non-background pixels must be less than 10 percent of total
+ pixels. You can use low-bit color for up to 5 percent of pixels on screens that support it.
+ You should also disable antialiasing in your paint styles for this mode. Make sure to test
+ your design on devices with low-bit ambient mode.</p>
+ <p>Other displays save power in ambient mode by not producing any color. When designing for
+ displays which do not use color in ambient mode, the background may be either black or
+ white.</p>
</div>
<div class="layout-content-col span-4">
<img src="{@docRoot}design/media/wear/Render_LowBit.png" width="200"
- height="" alt="" style="margin-top:-30px;margin-left:13px">
+ height="" alt="" style="margin-top:45px;margin-left:13px">
</div>
</div>
@@ -164,7 +171,7 @@ screens.</p>
</div>
<div class="layout-content-col span-4">
<img src="{@docRoot}design/media/wear/Render_1Bit.png" width="200"
- height="" alt="" style="margin-top:-30px;margin-left:13px">
+ height="" alt="" style="margin-top:-10px;margin-left:13px">
</div>
</div>
diff --git a/docs/html/distribute/tools/promote/device-art-resources/wear/thumb.png b/docs/html/distribute/tools/promote/device-art-resources/wear/thumb.png
new file mode 100644
index 0000000..adfe16f
--- /dev/null
+++ b/docs/html/distribute/tools/promote/device-art-resources/wear/thumb.png
Binary files differ
diff --git a/docs/html/distribute/tools/promote/device-art-resources/wear_round/port_back.png b/docs/html/distribute/tools/promote/device-art-resources/wear_round/port_back.png
new file mode 100644
index 0000000..0b3d04a
--- /dev/null
+++ b/docs/html/distribute/tools/promote/device-art-resources/wear_round/port_back.png
Binary files differ
diff --git a/docs/html/distribute/tools/promote/device-art-resources/wear_square/port_back.png b/docs/html/distribute/tools/promote/device-art-resources/wear_square/port_back.png
new file mode 100644
index 0000000..aa44795
--- /dev/null
+++ b/docs/html/distribute/tools/promote/device-art-resources/wear_square/port_back.png
Binary files differ
diff --git a/docs/html/distribute/tools/promote/device-art.jd b/docs/html/distribute/tools/promote/device-art.jd
index 3902b30..f583eb9 100644
--- a/docs/html/distribute/tools/promote/device-art.jd
+++ b/docs/html/distribute/tools/promote/device-art.jd
@@ -1,13 +1,13 @@
page.title=Device Art Generator
page.image=/images/device-art-ex-crop.jpg
-page.metaDescription=Drag and drop screenshots of your app into real device artwork, for better looking promotional images and improved visual context.
+page.metaDescription=Drag and drop screenshots of your app into device artwork, for better looking promotional images and improved visual context.
meta.tags="disttools, promoting, deviceart, marketing"
page.tags="device, deviceart, nexus, assets"
Xnonavpage=true
@jd:body
-<p>The device art generator enables you to quickly wrap app screenshots in real device artwork. This provides better visual context for your app screenshots on your website or in other promotional materials</p>
+<p>The device art generator enables you to quickly wrap app screenshots in device artwork. This provides better visual context for your app screenshots on your website or in other promotional materials</p>
<p class="note"><strong>Note</strong>: Do <em>not</em> use graphics created here in your 1024x500
feature image or screenshots for your Google Play app listing.</p>
@@ -41,6 +41,12 @@ feature image or screenshots for your Google Play app listing.</p>
<label for="output-glare">Screen Glare</label><br><br>
<a class="button" id="rotate-button">Rotate</a>
</p>
+ <p id="wear-customizations">
+ <input type="radio" id="output-square" name="output-wear" checked="checked" class="form-field-checkbutton">
+ <label for="output-square">Square</label><br>
+ <input type="radio" id="output-round" name="output-wear" class="form-field-checkbutton">
+ <label for="output-round">Round</label><br><br>
+ </p>
</div>
<div class="layout-content-col span-10">
<!-- position:relative fixes an issue where dragging an image out of a inline-block container
@@ -52,7 +58,7 @@ feature image or screenshots for your Google Play app listing.</p>
</div>
<div class="unsupported-browser" style="display: none">
- <p class="warning"><strong>Error:</strong> This page requires
+ <p class="warning"><strong>Error:</strong> This page requires
<span id="unsupported-browser-reason">certain features</span>, which your web browser
doesn't support. To continue, navigate to this page on a supported web browser, such as
<strong>Google Chrome</strong>.</p>
@@ -165,6 +171,10 @@ feature image or screenshots for your Google Play app listing.</p>
// Global constants
var MSG_INVALID_INPUT_IMAGE = 'Invalid screenshot provided. Screenshots must be PNG files '
+ 'matching the target device\'s screen aspect ratio in either portrait or landscape.';
+ var MSG_INVALID_WEAR_IMAGE = 'Invalid screenshot provided. Screenshots must be PNG files '
+ + 'matching the target device\'s screen aspect ratio.'
+ + ' Capture screenshots from a Wear emulator or device with '
+ + '<a href="http://developer.android.com/tools/debugging/debugging-studio.html#screenCap">Android Studio</a>.';
var MSG_NO_INPUT_IMAGE = 'Drag a screenshot (in PNG format) from your desktop onto a '
+ 'target device above.'
var MSG_GENERATING_IMAGE = 'Generating device art&hellip;';
@@ -270,6 +280,47 @@ feature image or screenshots for your Google Play app listing.</p>
portSize: [768,1280],
archived: true
},
+ {
+ id: 'wear',
+ title: 'Android Wear',
+ url: 'http://www.android.com/wear/',
+ physicalSize: 1.8,
+ physicalHeight: 1.8,
+ density: 'HDPI',
+ landRes: ['back'],
+ landOffset: [225,206],
+ portRes: ['back'],
+ portOffset: [200,214],
+ portSize: [320,320],
+ },
+ {
+ id: 'wear_square',
+ title: 'Android Wear Square',
+ url: 'http://www.android.com/wear/',
+ physicalSize: 1.8,
+ physicalHeight: 1.8,
+ density: 'HDPI',
+ landRes: ['back'],
+ landOffset: [225,206],
+ portRes: ['back'],
+ portOffset: [200,214],
+ portSize: [320,320],
+ hidden: true
+ },
+ {
+ id: 'wear_round',
+ title: 'Android Wear Round',
+ url: 'http://www.android.com/wear/',
+ physicalSize: 1.8,
+ physicalHeight: 1.8,
+ density: 'HDPI',
+ landRes: ['back'],
+ landOffset: [161,167],
+ portRes: ['back'],
+ portOffset: [128,134],
+ portSize: [320,320],
+ hidden: true
+ },
];
DEVICES = DEVICES.sort(function(x, y) { return x.physicalSize - y.physicalSize; });
@@ -343,15 +394,21 @@ feature image or screenshots for your Google Play app listing.</p>
$('#output').html(MSG_NO_INPUT_IMAGE);
$('#frame-customizations').hide();
+ $('#wear-customizations').hide();
$('#output-shadow, #output-glare').click(function() {
createFrame();
});
+ $('input[name="output-wear"]').change(function() {
+ createFrame();
+ });
+
// Build device list.
$.each(DEVICES, function() {
var resolution = this.actualResolution || this.portSize;
var scaleFactorText = '';
+ var deviceList = '.device-list.primary';
if (resolution[0] != this.portSize[0]) {
scaleFactorText = '<br>' + (100 * (this.portSize[0] / resolution[0])).toFixed(0) +
'% size output';
@@ -359,6 +416,12 @@ feature image or screenshots for your Google Play app listing.</p>
scaleFactorText = '<br>&nbsp;';
}
+ if (this.archived) {
+ deviceList = '.device-list.archived';
+ } else if (this.hidden) {
+ deviceList = '.device-list.hidden';
+ }
+
$('<li>')
.append($('<div>')
.addClass('thumb-container')
@@ -374,7 +437,7 @@ feature image or screenshots for your Google Play app listing.</p>
'<br>' + this.physicalSize + '" @ ' + this.density +
'<br>' + (resolution[0] + 'x' + resolution[1]) + scaleFactorText))
.data('deviceId', this.id)
- .appendTo(this.archived ? '.device-list.archive' : '.device-list.primary');
+ .appendTo(deviceList)
});
// Set up "older devices" expando.
@@ -406,7 +469,11 @@ feature image or screenshots for your Google Play app listing.</p>
evt.preventDefault();
loadImageFromFileList(evt.dataTransfer.files, function(data) {
if (data == null) {
- $('#output').html(MSG_INVALID_INPUT_IMAGE);
+ if (g_currentDevice.id == 'wear') {
+ $('#output').html(MSG_INVALID_WEAR_IMAGE);
+ }else {
+ $('#output').html(MSG_INVALID_INPUT_IMAGE);
+ }
return;
}
loadImageFromUri(data.uri, function(img) {
@@ -450,6 +517,14 @@ feature image or screenshots for your Google Play app listing.</p>
function createFrame() {
var port;
+ if (g_currentDevice.id == 'wear' || g_currentDevice.id == 'wear_square' || g_currentDevice.id == 'wear_round') {
+ if ($('#output-square').is(':checked')) {
+ g_currentDevice = getDeviceById('wear_square');
+ } else {
+ g_currentDevice = getDeviceById('wear_round');
+ }
+ }
+
var aspect1 = g_currentImage.naturalWidth / g_currentImage.naturalHeight;
var aspect2 = g_currentDevice.portSize[0] / g_currentDevice.portSize[1];
@@ -458,11 +533,18 @@ feature image or screenshots for your Google Play app listing.</p>
} else if (aspect1 == 1 / aspect2) {
port = false;
} else {
- alert('The screenshot must have an aspect ratio of ' +
+ if (g_currentDevice.id == 'wear_square' || g_currentDevice.id == 'wear_round') {
+ alert('The screenshot must have an aspect ratio of ' +
+ aspect2.toFixed(3) +
+ ' (ideally ' + g_currentDevice.portSize[0] + 'x' + g_currentDevice.portSize[1] + ').');
+ $('#output').html(MSG_INVALID_WEAR_IMAGE);
+ }else {
+ alert('The screenshot must have an aspect ratio of ' +
aspect2.toFixed(3) + ' or ' + (1 / aspect2).toFixed(3) +
' (ideally ' + g_currentDevice.portSize[0] + 'x' + g_currentDevice.portSize[1] +
' or ' + g_currentDevice.portSize[1] + 'x' + g_currentDevice.portSize[0] + ').');
- $('#output').html(MSG_INVALID_INPUT_IMAGE);
+ $('#output').html(MSG_INVALID_INPUT_IMAGE);
+ }
return;
}
@@ -497,9 +579,37 @@ feature image or screenshots for your Google Play app listing.</p>
ctx.drawImage(resourceImages['shadow'], 0, 0);
}
ctx.drawImage(resourceImages['back'], 0, 0);
- ctx.fillStyle = '#000';
- ctx.fillRect(offset[0], offset[1], size[0], size[1]);
- ctx.drawImage(g_currentImage, offset[0], offset[1], size[0], size[1]);
+
+ if (g_currentDevice.id == 'wear_round') {
+ var scratchCanvas = document.createElement('canvas');
+ scratchCanvas.width = width;
+ scratchCanvas.height = height;
+ var scratchCtx = scratchCanvas.getContext('2d');
+
+
+ //drawing code
+ scratchCtx.clearRect(offset[0], offset[1], scratchCanvas.width, scratchCanvas.height);
+
+ scratchCtx.globalCompositeOperation = 'source-over'; //default
+
+ scratchCtx.drawImage(g_currentImage, offset[0], offset[1], size[0], size[1]);
+
+ scratchCtx.fillStyle = '#fff'; //color doesn't matter, but we want full opacity
+ scratchCtx.globalCompositeOperation = 'destination-in';
+ scratchCtx.beginPath();
+ scratchCtx.arc(288, 294, size[0] / 2, 0, 2 * Math.PI, false);
+ scratchCtx.closePath();
+ scratchCtx.fill();
+
+ // After tinkering with the offset, the 1 in the x-position drew the image
+ // perfectly
+ ctx.drawImage(scratchCanvas, 1, 0);
+ } else {
+ ctx.fillStyle = '#000';
+ ctx.fillRect(offset[0], offset[1], size[0], size[1]);
+ ctx.drawImage(g_currentImage, offset[0], offset[1], size[0], size[1]);
+ }
+
if (resourceImages['fore'] && $('#output-glare').is(':checked')) {
ctx.drawImage(resourceImages['fore'], 0, 0);
}
@@ -546,7 +656,13 @@ feature image or screenshots for your Google Play app listing.</p>
.attr('data-downloadurl', ['image/png', filename, imageUrl].join(':')))
.appendTo($('#output').empty());
- $('#frame-customizations').show();
+ if (g_currentDevice.id == 'wear' || g_currentDevice.id == 'wear_round' || g_currentDevice.id == 'wear_square') {
+ $('#wear-customizations').show();
+ $('#frame-customizations').hide();
+ } else {
+ $('#frame-customizations').show();
+ $('#wear-customizations').hide();
+ }
}
}
diff --git a/docs/html/google/gcm/adv.jd b/docs/html/google/gcm/adv.jd
deleted file mode 100644
index 95497e3..0000000
--- a/docs/html/google/gcm/adv.jd
+++ /dev/null
@@ -1,410 +0,0 @@
-page.title=GCM Advanced Topics
-@jd:body
-
-<div id="qv-wrapper">
-<div id="qv">
-
-<h2>Quickview</h2>
-
-<ul>
-<li>Learn more about GCM advanced features.</li>
-</ul>
-
-
-<h2>In this document</h2>
-
-<ol>
-<li><a href="#lifetime">Lifetime of a Message</a></li>
-<li><a href="#throttling">Throttling</a></li>
-<li><a href="#reg-state">Keeping the Registration State in Sync</a>
- <ol>
- <li><a href="#canonical">Canonical IDs</a></li>
- </ol>
-</li>
-<li><a href="#retry">Automatic Retry Using Exponential Back-Off</a></li>
-<li><a href="#unreg">Unregistration</a>
- <ol>
- <li><a href="#unreg-why">Why you should rarely unregister</a></li>
- <li><a href="#unreg-how">How unregistration works</a></li>
- </ol>
-</li>
-<li><a href="#collapsible">Send-to-Sync vs. Messages with Payload</a>
- <ol>
- <li><a href="#s2s">Send-to-sync messages</a></li>
- <li><a href="#payload">Messages with payload</a></li>
-<li><a href="#which">Which should I use?</a></li>
- </ol>
-</li>
-<li><a href="#ttl">Setting an Expiration Date for a Message</a> </li>
-<li><a href="#throttling"></a><a href="#multi-senders">Receiving Messages from
-Multiple Senders</a></li>
-</ol>
-
-</div>
-</div>
-<p>This document covers advanced topics for GCM.</p>
-
-
-
-
-<h2 id="msg-lifetime">Lifetime of a Message</h2>
-<p>When a 3rd-party server posts a message to GCM and receives a message ID back,
-it does not mean that the message was already delivered to the device. Rather, it
-means that it was accepted for delivery. What happens to the message after it is
-accepted depends on many factors.</p>
-
-<p>In the best-case scenario, if the device is connected to GCM, the screen is on,
-and there are no throttling restrictions (see <a href="#throttling">Throttling</a>),
-the message will be delivered right away.</p>
-
-<p>If the device is connected but idle, the message will still be
-delivered right away unless the <code>delay_while_idle</code> flag is set to true.
-Otherwise, it will be stored in the GCM servers until the device is awake. And
-that's where the <code>collapse_key</code> flag plays a role: if there is already
-a message with the same collapse key (and registration ID) stored and waiting for
-delivery, the old message will be discarded and the new message will take its place
-(that is, the old message will be collapsed by the new one). However, if the collapse
-key is not set, both the new and old messages are stored for future delivery.
-Collapsible messages are also called <a href="#s2s">send-to-sync messages</a>.</p>
-
-<p class="note"><strong>Note:</strong> There is a limit on how many messages can
-be stored without collapsing. That limit is currently 100. If the limit is reached,
-all stored messages are discarded. Then when the device is back online, it receives
-a special message indicating that the limit was reached. The application can then
-handle the situation properly, typically by requesting a full sync.
-<br><br>
-Likewise, there is a limit on how many <code>collapse_key</code>s you can have for
-a particular device. GCM allows a maximum of 4 different collapse keys to be used
-by the GCM server per device
-any given time. In other words, the GCM server can simultaneously store 4 different
-send-to-sync messages, each with a different collapse key. If you exceed this number
-GCM will only keep 4 collapse keys, with no guarantees about which ones they will be.
-See <a href="#s2s">Send-to-sync messages</a> for more information.
-</p>
-
-<p>If the device is not connected to GCM, the message will be stored until a
-connection is established (again respecting the collapse key rules). When a connection
-is established, GCM will deliver all pending messages to the device, regardless of
-the <code>delay_while_idle</code> flag. If the device never gets connected again
-(for instance, if it was factory reset), the message will eventually time out and
-be discarded from GCM storage. The default timeout is 4 weeks, unless the
-<code>time_to_live</code> flag is set.</p>
-
-<p>Finally, when GCM attempts to deliver a message to the device and the
-application was uninstalled, GCM will discard that message right away and
-invalidate the registration ID. Future attempts to send a message to that device
-will get a <code>NotRegistered</code> error. See <a href="#unreg">
-How Unregistration Works</a> for more information.</p>
-<p>Although is not possible to track the status of each individual message, the
-Google Cloud Console stats are broken down by messages sent to device, messages
-collapsed, and messages waiting for delivery.</p>
-
-<h2 id="throttling">Throttling</h2>
-<p>To prevent abuse (such as sending a flood of messages to a device) and
-to optimize for the overall network efficiency and battery life of
-devices, GCM implements throttling of messages using a token bucket
-scheme. Messages are throttled on a per application and per <a href="#collapsible">collapse
-key</a> basis (including non-collapsible messages). Each application
-collapse key is granted some initial tokens, and new tokens are granted
-periodically therefter. Each token is valid for a single message sent to
-the device. If an application collapse key exhausts its supply of
-available tokens, new messages are buffered in a pending queue until
-new tokens become available at the time of the periodic grant. Thus
-throttling in between periodic grant intervals may add to the latency
-of message delivery for an application collapse key that sends a large
-number of messages within a short period of time. Messages in the pending
-queue of an application collapse key may be delivered before the time
-of the next periodic grant, if they are piggybacked with messages
-belonging to a non-throttled category by GCM for network and battery
-efficiency reasons.</p>
-
-<h2 id="reg-state">Keeping the Registration State in Sync</h2>
-<p>Whenever the application registers as described in
-<a href="{@docRoot}google/gcm/client.html">Implementing GCM Client</a>,
-it should save the registration ID for future use, pass it to the
-3rd-party server to complete the registration, and keep track of
-whether the server completed the registration. If the server fails
-to complete the registration, it should try again or unregister from GCM.</p>
-
-<p>There are also two other scenarios that require special care:</p>
-<ul>
- <li>Application update</li>
- <li>Backup and restore
- </li>
-</ul>
-<p>When an application is updated, it should invalidate its existing registration
-ID, as it is not guaranteed to work with the new version. Because there is no
-lifecycle method called when the application is updated, the best way to achieve
-this validation is by storing the current application version when a registration
-ID is stored. Then when the application is started, compare the stored value with
-the current application version. If they do not match, invalidate the stored data
-and start the registration process again.</p>
-
-<p>Similarly, you should not save the registration ID when an application is
-backed up. This is because the registration ID could become invalid by the time
-the application is restored, which would put the application in an invalid state
-(that is, the application thinks it is registered, but the server and GCM do not
-store that registration ID anymore&mdash;thus the application will not get more
-messages).</p>
-<h3 id="canonical">Canonical IDs</h3>
-<p>On the server side, as long as the application is behaving well, everything
-should work normally. However, if a bug in the application triggers multiple
-registrations for the same device, it can be hard to reconcile state and you might
-end up with duplicate messages.</p>
-<p>GCM provides a facility called &quot;canonical registration IDs&quot; to easily
-recover from these situations. A canonical registration ID is defined to be the ID
-of the last registration requested by your application. This is the ID that the
-server should use when sending messages to the device.</p>
-<p>If later on you try to send a message using a different registration ID, GCM
-will process the request as usual, but it will include the canonical registration
-ID in the <code>registration_id</code> field of the response. Make sure to replace
-the registration ID stored in your server with this canonical ID, as eventually
-the ID you're using will stop working.</p>
-
-<h2 id="retry">Automatic Retry Using Exponential Back-Off</h2>
-
-<p>When registration or unregistration fails, the app should retry the failed operation.</p>
-<p>In the simplest case, if your application attempts to register and GCM is not a
-fundamental part of the application, the application could simply ignore the error
-and try to register again the next time it starts. Otherwise, it should retry the
-previous operation using exponential back-off. In exponential back-off, each time
-there is a failure, it should wait twice the previous amount of time before trying
-again. If the register (or unregister) operation was synchronous, it could be retried
-in a simple loop. However, since it is asynchronous, the best approach is to schedule
-a {@link android.app.PendingIntent} to retry the operation.
-
-<h2 id="unreg">Unregistration</h2>
-
-<p>This section explains when you should unregister in GCM and what happens
-when you do.</p>
-
-<h3 id="unreg-why">Why you should rarely unregister</h3>
-
-<p>A registration ID (regID) represents a particular Android application running
-on a particular device. You should only need to unregister in rare cases, such as
-if you want an app to stop receiving messages, or if you suspect that the regID has
-been compromised. In general, though, once an app has a regID, you shouldn't need
-to change it.</p>
-
-<p>In particular, you should never unregister your app as a mechanism for
-logout or for switching between users, for the following reasons:</p>
-
-<ul>
- <li>A regID maps an app to a device. It isn't associated with a particular
- logged in user. If you unregister and then re-register, GCM may return the same
- ID or a different ID&mdash;there's no guarantee either way.</li>
-
- <li>Unregistration may take up to 5 minutes to propagate.</li>
- <li>After unregistration, re-registration may again take up to 5 minutes to
-propagate. During this time messages may be rejected due to the state of being
-unregistered, and after all this, messages may still go to the wrong user.</li>
-</ul>
-
-
-<p>The solution is to manage your own mapping between users, the regID, and
-individual messages:</p>
-
-<ul>
- <li>Your app server should maintain a mapping between the current user
-and the regID. This should include information about which user is supposed to
-receive a particular message.</li>
- <li>The app running on the device should check to ensure that messages it
-receives match the logged in user.</li>
-</ul>
-
-
-<h3 id="unreg-how">How unregistration works</h3>
-
-<p>An application can be automatically unregistered after it is uninstalled from
-the device. However, this process does not happens right away, as Android does not
-provide an uninstall callback. What happens in this scenario is as follows:</p>
-<ol>
- <li>The end user uninstalls the application.</li>
- <li>The 3rd-party server sends a message to GCM server.</li>
- <li>The GCM server sends the message to the device.</li>
- <li>The GCM client receives the message and queries Package Manager about
-whether there are broadcast receivers configured to receive it, which returns
-<code>false</code>.
-</li>
- <li>The GCM client informs the GCM server that the application was uninstalled.</li>
- <li>The GCM server marks the registration ID for deletion.</li>
- <li>The 3rd-party server sends a message to GCM.</li>
- <li>The GCM returns a <code>NotRegistered</code> error message to the 3rd-party server.</li>
- <li>The 3rd-party deletes the registration ID.
- </li>
-</ol>
-
-<p class ="note"><strong>Note:</strong> The GCM client is the Google Cloud
-Messaging framework present on the device.</p>
-
-<p>Note that it might take a while for the registration ID be completely removed
-from GCM. Thus it is possible that messages sent during step 7 above gets a valid
-message ID as response, even though the message will not be delivered to the device.
-Eventually, the registration ID will be removed and the server will get a
-<code>NotRegistered</code> error, without any further action being required from
-the 3rd-party server (this scenario happens frequently while an application is
-being developed and tested).</p>
-
-<h2 id="collapsible">Send-to-Sync vs. Messages with Payload</h2>
-
-<p>Every message sent in GCM has the following characteristics:</p>
-<ul>
- <li>It has a payload limit of 4096 bytes.</li>
- <li>By default, it is stored by GCM for 4 weeks.</li>
-</ul>
-
-<p>But despite these similarities, messages can behave very differently depending
-on their particular settings. One major distinction between messages is whether
-they are collapsed (where each new message replaces the preceding message) or not
-collapsed (where each individual message is delivered). Every message sent in GCM
-is either a &quot;send-to-sync&quot; (collapsible) message or a &quot;message with
-payload&quot; (non-collapsible message). These concepts are described in more
-detail in the following sections.</p>
-
-<h3 id="s2s">Send-to-sync messages</h3>
-
-<p>A send-to-sync (collapsible) message is often a &quot;tickle&quot; that tells
-a mobile application to sync data from the server. For example, suppose you have
-an email application. When a user receives new email on the server, the server
-pings the mobile application with a &quot;New mail&quot; message. This tells the
-application to sync to the server to pick up the new email. The server might send
-this message multiple times as new mail continues to accumulate, before the application
-has had a chance to sync. But if the user has received 25 new emails, there's no
-need to preserve every &quot;New mail&quot; message. One is sufficient. Another
-example would be a sports application that updates users with the latest score.
-Only the most recent message is relevant, so it makes sense to have each new
-message replace the preceding message. </p>
-
-<p>The email and sports applications are cases where you would probably use the
-GCM <code>collapse_key</code> parameter. A <em>collapse key</em> is an arbitrary
-string that is used to collapse a group of like messages when the device is offline,
-so that only the most recent message gets sent to the client. For example,
-&quot;New mail,&quot; &quot;Updates available,&quot; and so on</p>
-<p>GCM allows a maximum of 4 different collapse keys to be used by the GCM server
-at any given time. In other words, the GCM server can simultaneously store 4
-different send-to-sync messages per device, each with a different collapse key.
-For example, Device A can have A1, A2, A3, and A4. Device B can have B1, B2, B3,
-and B4, and so on. If you exceed this number GCM will only keep 4 collapse keys, with no
-guarantees about which ones they will be.</p>
-
-<h3 id="payload">Messages with payload</h3>
-
-<p>Unlike a send-to-sync message, every &quot;message with payload&quot;
-(non-collapsible message) is delivered. The payload the message contains can be
-up to 4kb. For example, here is a JSON-formatted message in an IM application in
-which spectators are discussing a sporting event:</p>
-
-<pre class="prettyprint pretty-json">{
- "registration_id" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
- "data" : {
- "Nick" : "Mario",
- "Text" : "great match!",
- "Room" : "PortugalVSDenmark",
- },
-}</pre>
-
-<p>A &quot;message with payload&quot; is not simply a &quot;ping&quot; to the
-mobile application to contact the server to fetch data. In the aforementioned IM
-application, for example, you would want to deliver every message, because every
-message has different content. To specify a non-collapsible message, you simply
-omit the <code>collapse_key</code> parameter. Thus GCM will send each message
-individually. Note that the order of delivery is not guaranteed.</p>
-
-<p>GCM will store up to 100 non-collapsible messages. After that, all messages
-are discarded from GCM, and a new message is created that tells the client how
-far behind it is. The message is delivered through a regular
-<code>com.google.android.c2dm.intent.RECEIVE</code> intent with the
-extra <code>message_type</code>, for which the value is always the string
-&quot;deleted_messages&quot;.</p>
-
-<p>The application should respond by syncing with the server to recover the
-discarded messages. </p>
-
-<h3 id="which">Which should I use?</h3>
- <p>If your application does not need to use non-collapsible messages, collapsible
-messages are a better choice from a performance standpoint, because they put less
-of a burden on the device battery. However, if you use collapsible messages, remember that
-<strong>GCM only allows a maximum of 4 different collapse keys to be used by the GCM server
-per device at any given time</strong>. You must not exceed this number, or it could cause
-unpredictable consequences.</p>
-
-<h2 dir="ltr" id="ttl">Setting an Expiration Date for a Message</h2>
-<p>The Time to Live (TTL) feature lets the sender specify the maximum lifespan
-of a message using the <code>time_to_live</code> parameter in the send request.
-The value of this parameter must be a duration from 0 to 2,419,200 seconds, and
-it corresponds to the maximum period of time for which GCM will store and try to
-deliver the message. Requests that don't contain this field default to the maximum
-period of 4 weeks.</p>
-<p>Here are some possible uses for this feature:</p>
-<ul>
- <li>Video chat incoming calls</li>
- <li>Expiring invitation events</li>
- <li>Calendar events</li>
-</ul>
-<h3 id="bg">Background </h3>
-<p>GCM will usually deliver messages immediately after they are sent. However,
-this might not always be possible. For example, the device could be turned off,
-offline, or otherwise unavailable. In other cases, the sender itself might request
-that messages not be delivered until the device becomes active by using the
-<code>delay_while_idle</code> flag. Finally, GCM might intentionally delay messages
-to prevent an application from consuming excessive resources and negatively
-impacting battery life.</p>
-
-<p>When this happens, GCM will store the message and deliver it as soon as it's
-feasible. While this is fine in most cases, there are some applications for which
-a late message might as well never be delivered. For example, if the message is
-an incoming call or video chat notification, it will only be meaningful for a
-small period of time before the call is terminated. Or if the message is an
-invitation to an event, it will be useless if received after the event has ended.</p>
-
-<p>Another advantage of specifying the expiration date for a message is that GCM
-will never throttle messages with a <code>time_to_live</code> value of 0 seconds.
-In other words, GCM will guarantee best effort for messages that must be delivered
-&quot;now or never.&quot; Keep in mind that a <code>time_to_live</code> value of
-0 means messages that can't be delivered immediately will be discarded. However,
-because such messages are never stored, this provides the best latency for
-sending notifications.</p>
-
-<p>Here is an example of a JSON-formatted request that includes TTL:</p>
-<pre class="prettyprint pretty-json">
-{
- "collapse_key" : "demo",
- "delay_while_idle" : true,
- "registration_ids" : ["xyz"],
- "data" : {
- "key1" : "value1",
- "key2" : "value2",
- },
- "time_to_live" : 3
-},
-</pre>
-
-
-<h2 id="multi-senders">Receiving Messages from Multiple Senders</h2>
-
-<p>GCM allows multiple parties to send messages to the same application. For
-example, suppose your application is an articles aggregator with multiple
-contributors, and you want each of them to be able to send a message when they
-publish a new article. This message might contain a URL so that the application
-can download the article. Instead of having to centralize all sending activity in
-one location, GCM gives you the ability to let each of these contributors send
-its own messages.</p>
-
-<p>To make this possible, all you need to do is have each sender generate its own
-project number. Then include those IDs in the sender field, separated by commas,
-when requesting a registration. Finally, share the registration ID with your
-partners, and they'll be able to send messages to your application using their
-own authentication keys.</p>
-<p>This code snippet illustrates this feature. Senders are passed as an intent
-extra in a comma-separated list:</p>
-
-<pre class="prettyprint pretty-java">Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
-intent.setPackage(GSF_PACKAGE);
-intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
- PendingIntent.getBroadcast(context, 0, new Intent(), 0));
-String senderIds = &quot;968350041068,652183961211&quot;;
-intent.putExtra(GCMConstants.EXTRA_SENDER, senderIds);
-ontext.startService(intent);
- </pre>
-
-<p>Note that there is limit of 100 multiple senders.</p>
diff --git a/docs/html/google/gcm/c2dm.jd b/docs/html/google/gcm/c2dm.jd
index 5c4a86e..fc95c2b 100644
--- a/docs/html/google/gcm/c2dm.jd
+++ b/docs/html/google/gcm/c2dm.jd
@@ -79,7 +79,7 @@ page.title=Migration
<h3 id="interop">Relationship between C2DM and GCM</h3>
-<p>C2DM and GCM are not interoperable. For example, you cannot post notifications from GCM to C2DM registration IDs, nor can you use C2DM registration IDs as GCM registration IDs. From your server-side application, you must keep keep track of whether a registration ID is from C2DM or GCM and use the proper endpoint. </p>
+<p>C2DM and GCM are not interoperable. For example, you cannot post notifications from GCM to C2DM registration IDs, nor can you use C2DM registration IDs as GCM registration IDs. From your server-side application, you must keep track of whether a registration ID is from C2DM or GCM and use the proper endpoint. </p>
<p>As you transition from C2DM to GCM, your server needs to be aware of whether a given registration ID
contains an old C2DM sender or a new GCM project number. This is the approach we recommend: have the new app version (the one that uses GCM) send a bit along with the registration ID. This bit tells your server that this registration ID is for GCM. If you don't get the extra bit, you mark the registration ID as C2DM. Once no more valid registration IDs are marked as C2DM, you can complete the migration.</p>
@@ -87,13 +87,11 @@ contains an old C2DM sender or a new GCM project number. This is the approach we
<h2 id="migrating">Migrating Your Apps</h2>
<p>This section describes how to move existing C2DM apps to GCM.</p>
<h3 id="client">Client changes</h3>
-<p>Migration is simple! The only change required in the application is replacing the email account passed in the sender parameter of the registration intent with the project number generated when signing up for the new service. For example:</p>
-<pre class="prettyprint pretty-java">Intent registrationIntent = new Intent(&quot;com.google.android.c2dm.intent.REGISTER&quot;);
-// sets the app name in the intent
-registrationIntent.putExtra(&quot;app&quot;, PendingIntent.getBroadcast(this, 0, new Intent(), 0));
-registrationIntent.putExtra(&quot;sender&quot;, senderID);
-startService(registrationIntent);</pre>
+<p>Migration is simple! Just re-register the client app for your target GCM-enabled platform. For
+ example, see <a href="{@docRoot}google/gcm/client.html#sample-register">Register for GCM</a></p>
+
<p>After receiving a response from GCM, the registration ID obtained must be sent to the application server. When doing this, the application should indicate that it is sending a GCM registration ID so that the server can distinguish it from existing C2DM registrations.</p>
+
<h3 id="server">Server changes</h3>
<p>When the application server receives a GCM registration ID, it should store it and mark it as such.</p>
<p>Sending messages to GCM devices requires a few changes:</p>
diff --git a/docs/html/google/gcm/ccs.jd b/docs/html/google/gcm/ccs.jd
index 6332b8d..143b057 100644
--- a/docs/html/google/gcm/ccs.jd
+++ b/docs/html/google/gcm/ccs.jd
@@ -36,6 +36,7 @@ page.title=GCM Cloud Connection Server (XMPP)
<h2>See Also</h2>
<ol class="toc">
+<li><a href="server-ref.html">Server Reference</a></li>
<li><a href="{@docRoot}google/gcm/http.html">HTTP</a></li>
<li><a href="{@docRoot}google/gcm/gs.html">Getting Started</a></li>
<li><a href="{@docRoot}google/gcm/server.html">Implementing GCM Server</a></li>
@@ -73,8 +74,8 @@ Play services platform. Upstream messaging is available through the
APIs. For examples, see
<a href="#implement">Implementing an XMPP-based App Server</a>.</p>
-<p class="note"><strong>Note:</strong> See
-<a href="server.html#params">Implementing GCM Server</a> for a list of all the message
+<p class="note"><strong>Note:</strong> See the
+<a href="server-ref.html">Server Reference</a> for a list of all the message
parameters and which connection server(s) supports them.</p>
<h2 id="connecting">Establishing a Connection</h2>
@@ -176,8 +177,8 @@ operation and your server needs to resend the messages. See
<a href="#flow">Flow Control</a> for details.
</p>
-<p class="note"><strong>Note:</strong> See
-<a href="server.html#params">Implementing GCM Server</a> for a list of all the message
+<p class="note"><strong>Note:</strong> See the
+<a href="server-ref.html">Server Reference</a> for a list of all the message
parameters and which connection server(s) supports them.</p>
<h3 id="request">Request format</h3>
@@ -278,56 +279,11 @@ message is &quot;nack&quot;. A NACK message contains:</p>
&lt;/message&gt;
</pre>
-<p>The following table lists NACK error codes. Unless otherwise
+<p>See the <a href="server-ref.html#table11">Server Reference</a> for a complete list of the
+NACK error codes. Unless otherwise
indicated, a NACKed message should not be retried. Unexpected NACK error codes
should be treated the same as {@code INTERNAL_SERVER_ERROR}.</p>
-<p class="table-caption" id="table1">
- <strong>Table 1.</strong> NACK error codes.</p>
-
-<table border="1">
-<tr>
-<th>Error Code</th>
-<th>Description</th>
-</tr>
-<tr>
-<td>{@code BAD_ACK}</td>
-<td>The ACK message is improperly formed.</td>
-</tr>
-<tr>
-<td>{@code BAD_REGISTRATION}</td>
-<td>The device has a registration ID, but it's invalid or expired.</td>
-</tr>
-<tr>
-<td>{@code CONNECTION_DRAINING}</td>
-<td>The message couldn't be processed because the connection is draining. The
-message should be immediately retried over another connection.</td>
-</tr>
-<tr>
-<td>{@code DEVICE_UNREGISTERED}</td>
-<td>The device is not registered.</td>
-</tr>
-<tr>
-<td>{@code INTERNAL_SERVER_ERROR}</td>
-<td>The server encountered an error while trying to process the request.</td>
-</tr>
-<tr>
-<td>{@code INVALID_JSON}</td>
-<td>The JSON message payload is not valid.</td>
-</tr>
-<td>{@code DEVICE_MESSAGE_RATE_EXCEEDED}</td>
-<td>The rate of messages to a particular device is too high. You should reduce
-the number of messages sent to this device and should not immediately retry
-sending to this device. This error code is replacing {@code QUOTA_EXCEEDED}.</td>
-</tr>
-<tr>
- <td>{@code SERVICE_UNAVAILABLE}</td>
- <td>CCS is not currently able to process the message. The
- message should be retried over the same connection using exponential backoff
- with an initial delay of 1 second.</td>
-</tr>
-</table>
-
<h4 id="stanza">Stanza error</h4>
<p>You can also get a stanza error in certain cases.
diff --git a/docs/html/google/gcm/client.jd b/docs/html/google/gcm/client.jd
index d44ee3c..9cb3f84 100644
--- a/docs/html/google/gcm/client.jd
+++ b/docs/html/google/gcm/client.jd
@@ -1,4 +1,4 @@
-page.title=Implementing GCM Client
+page.title=Implementing GCM Client on Android
page.tags=cloud,push,messaging
@jd:body
@@ -15,8 +15,8 @@ page.tags=cloud,push,messaging
<ol class="toc">
<li><a href="#sample-play">Check for Google Play Services APK</a></li>
<li><a href="#sample-register">Register for GCM</a></li>
- <li><a href="#sample-send">Send a message</a></li>
- <li><a href="#sample-receive">Receive a message</a></li>
+ <li><a href="#sample-receive">Receive a downstream message</a></li>
+ <li><a href="#sample-send">Send an upstream message</a></li>
</ol>
<li><a href="#run">Running the Sample</a></li>
<li><a href="#stats">Viewing Statistics</a></li>
@@ -34,14 +34,26 @@ page.tags=cloud,push,messaging
</div>
</div>
-<p>A Google Cloud Messaging (GCM) client is a GCM-enabled app that runs on an
+<p>A Google Cloud Messaging (GCM) Android client is a GCM-enabled app that runs on an
Android device. To write your client code, we recommend that you use the
<a href="{@docRoot}reference/com/google/android/gms/gcm/package-summary.html">
-GCM APIs</a>.
-The client helper library that was offered in previous versions of GCM still works,
-but it has been superseded by the more efficient
-<a href="{@docRoot}reference/com/google/android/gms/gcm/package-summary.html">
-GCM APIs</a>.</p>
+{@code GoogleCloudMessaging}</a> API.</p>
+
+<p>Here are the requirements for running a GCM Android client:</p>
+
+<ul>
+ <li>At a bare minimum, GCM requires devices running Android 2.2 or higher that also have the
+Google Play Store application installed, or an emulator running Android 2.2
+with Google APIs. Note that you are not limited to deploying your
+Android applications through Google Play Store.</li>
+ <li>However, if you want to continue to use new GCM features that are distributed
+through Google Play Services, the device must be running Android 2.3 or higher, or
+you can use an emulator running Android 2.3 with Google APIs.</li>
+<li>On Android devices, GCM uses an existing connection for Google services. For
+pre-3.0 devices, this requires users to set up their Google accounts on their mobile
+devices. A Google account is not a requirement on devices running Android 4.0.4 or higher.</li>
+
+</ul>
<p>A full GCM implementation requires both a client implementation and a server
implementation. For more
@@ -58,7 +70,7 @@ registration ID), and a broadcast receiver to receive messages sent by GCM.
<p>To write your client application, use the
<a href="{@docRoot}reference/com/google/android/gms/gcm/package-summary.html">
-GCM APIs</a>.
+{@code GoogleCloudMessaging}</a> API.
To use this API, you must set up your project to use the Google Play services SDK,
as described in <a href="/google/play-services/setup.html">Setup Google Play
Services SDK</a>.</p>
@@ -88,9 +100,6 @@ If you're using Android Studio, this is the string to add to the
the Android application can register and receive messages.</li>
<li>The <code>android.permission.INTERNET</code> permission so the Android
application can send the registration ID to the 3rd party server.</li>
- <li>The <code>android.permission.GET_ACCOUNTS</code> permission as GCM requires
-a Google account (necessary only if if the device is running a version lower than
-Android 4.0.4)</li>
<li>The <code>android.permission.WAKE_LOCK</code> permission so the application
can keep the processor from sleeping when a message is received. Optional&mdash;use
only if the app wants to keep the device from sleeping.</li>
@@ -101,7 +110,7 @@ pattern&mdash;otherwise the Android application will not receive the messages.</
<li>A receiver for <code>com.google.android.c2dm.intent.RECEIVE</code>, with
the category set
as <code>applicationPackage</code>. The receiver should require the
-<code>com.google.android.c2dm.SEND</code> permission, so that only the GCM
+<code>com.google.android.c2dm.permission.SEND</code> permission, so that only the GCM
Framework can send a message to it. If your app uses an {@link android.app.IntentService}
(not required, but a common pattern), this receiver should be an instance of
{@link android.support.v4.content.WakefulBroadcastReceiver}.
@@ -324,8 +333,8 @@ private String getRegistrationId(Context context) {
return "";
}
// Check if app was updated; if so, it must clear the registration ID
- // since the existing regID is not guaranteed to work with the new
- // app version.
+ // since the existing registration ID is not guaranteed to work with
+ // the new app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
@@ -340,14 +349,14 @@ private String getRegistrationId(Context context) {
*/
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
- // how you store the regID in your app is up to you.
+ // how you store the registration ID in your app is up to you.
return getSharedPreferences(DemoActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}</pre>
<p>If the registration ID doesn't exist or the app was updated,
{@code getRegistrationId()} returns an empty string
-to indicate that the app needs to get a new regID. {@code getRegistrationId()} calls
+to indicate that the app needs to get a new registration ID. {@code getRegistrationId()} calls
the following method to check the app version:</p>
<pre>/**
@@ -400,7 +409,7 @@ private void registerInBackground() {
// will send upstream messages to a server that echo back the
// message using the 'from' address in the message.
- // Persist the regID - no need to register again.
+ // Persist the registration ID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
@@ -433,7 +442,8 @@ private void sendRegistrationIdToBackend() {
<p>After registering, the app calls {@code storeRegistrationId()} to store the
registration ID in shared preferences for future use. This is just one way of
-persisting a regID. You might choose to use a different approach in your app:</p>
+persisting a registration ID. You might choose to use a different approach in
+your app:</p>
<pre>/**
* Stores the registration ID and app versionCode in the application's
@@ -455,64 +465,22 @@ private void storeRegistrationId(Context context, String regId) {
<h4 id="reg-errors">Handle registration errors</h4>
<p>As stated above, an Android app must register with GCM servers and get a registration ID
-(regID) before it can receive messages. A given regID is not guaranteed to last indefinitely,
-so the first thing your app should always do is check to make sure it has a valid regID
-(as shown in the code snippets above).</p>
+before it can receive messages. A given registration ID is not guaranteed to last indefinitely,
+so the first thing your app should always do is check to make sure it has a valid
+registration ID (as shown in the code snippets above).</p>
-<p>In addition to confirming that it has a valid regID, your app should be prepared to handle
+<p>In addition to confirming that it has a valid registration ID, your app should be prepared to handle
the registration error {@code TOO_MANY_REGISTRATIONS}. This error indicates that the device
has too many apps registered with GCM. The error only occurs in cases where there are
extreme numbers of apps, so it should not affect the average user. The remedy is to prompt
-the user to delete some of the other GCM-enabled apps from the device to make
+the user to delete some of the other client apps from the device to make
room for the new one.</p>
-
-<h3 id="sample-send">Send a message</h3>
-<p>When the user clicks the app's <strong>Send</strong> button, the app sends an
-upstream message using the
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a> API. In order to receive the upstream message,
-your server should be connected to CCS. You can use one of the demo servers in
-<a href="ccs.html#implement">Implementing an XMPP-based App Server</a> to run the sample and connect
-to CCS.</p>
-
-<pre>public void onClick(final View view) {
- if (view == findViewById(R.id.send)) {
- new AsyncTask<Void, Void, String>() {
- &#64;Override
- protected String doInBackground(Void... params) {
- String msg = "";
- try {
- Bundle data = new Bundle();
- data.putString("my_message", "Hello World");
- data.putString("my_action",
- "com.google.android.gcm.demo.app.ECHO_NOW");
- String id = Integer.toString(msgId.incrementAndGet());
- gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
- msg = "Sent message";
- } catch (IOException ex) {
- msg = "Error :" + ex.getMessage();
- }
- return msg;
- }
-
- &#64;Override
- protected void onPostExecute(String msg) {
- mDisplay.append(msg + "\n");
- }
- }.execute(null, null, null);
- } else if (view == findViewById(R.id.clear)) {
- mDisplay.setText("");
- }
-}</pre>
-
-<h3 id="sample-receive">Receive a message</h3>
+<h3 id="sample-receive">Receive a downstream message</h3>
<p>As described above in <a href="#manifest">Step 2</a>, the app includes a
{@link android.support.v4.content.WakefulBroadcastReceiver} for the <code>com.google.android.c2dm.intent.RECEIVE</code>
-intent. A broadcast receiver is the mechanism GCM uses to deliver messages. When {@code onClick()}
-calls {@code gcm.send()}, it triggers the broadcast receiver's {@code onReceive()}
-method, which has the responsibility of making sure that the GCM message gets handled.</p>
+intent. A broadcast receiver is the mechanism GCM uses to deliver messages. </p>
<p>A {@link android.support.v4.content.WakefulBroadcastReceiver} is a special type of
broadcast receiver that takes care of
creating and managing a
@@ -646,6 +614,46 @@ public class GcmIntentService extends IntentService {
}
}</pre>
+
+<h3 id="sample-send">Send an upstream message</h3>
+<p>When the user clicks the app's <strong>Send</strong> button, the app sends an
+upstream message using the
+<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
+{@code GoogleCloudMessaging}</a> API. In order to receive the upstream message,
+your server should be connected to CCS. You can use one of the demo servers in
+<a href="ccs.html#implement">Implementing an XMPP-based App Server</a> to run the sample and connect
+to CCS.</p>
+
+<pre>public void onClick(final View view) {
+ if (view == findViewById(R.id.send)) {
+ new AsyncTask<Void, Void, String>() {
+ &#64;Override
+ protected String doInBackground(Void... params) {
+ String msg = "";
+ try {
+ Bundle data = new Bundle();
+ data.putString("my_message", "Hello World");
+ data.putString("my_action",
+ "com.google.android.gcm.demo.app.ECHO_NOW");
+ String id = Integer.toString(msgId.incrementAndGet());
+ gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
+ msg = "Sent message";
+ } catch (IOException ex) {
+ msg = "Error :" + ex.getMessage();
+ }
+ return msg;
+ }
+
+ &#64;Override
+ protected void onPostExecute(String msg) {
+ mDisplay.append(msg + "\n");
+ }
+ }.execute(null, null, null);
+ } else if (view == findViewById(R.id.clear)) {
+ mDisplay.setText("");
+ }
+}</pre>
+
<h2 id="run">Running the Sample</h2>
<p>To run the sample:</p>
diff --git a/docs/html/google/gcm/gcm.jd b/docs/html/google/gcm/gcm.jd
index 3d6594d..4e345b3 100644
--- a/docs/html/google/gcm/gcm.jd
+++ b/docs/html/google/gcm/gcm.jd
@@ -9,58 +9,24 @@ page.title=Overview
<ol class="toc">
<li><a href="#key">Key Concepts</a></li>
<li><a href="#arch">Architectural Overview</a></li>
- <li><a href="#lifecycle">Lifecycle Flow</a>
- <ol class="toc">
- <li><a href="#register">Enable GCM</a></li>
- <li><a href="#push-process">Send a message</a></li>
- <li><a href="#receiving">Receive a message</a></li>
- </ol>
- </li>
+ <li><a href="#lifecycle">Lifecycle Flow</a></li>
+ <li><a href="#reg">Register to enable GCM</a></li>
</ol>
</div>
</div>
-<p>Google Cloud Messaging (GCM) for Android is a free service that helps
-developers send data from servers to their Android applications on Android
-devices, and upstream messages from the user's device back to the cloud.
-This could be a lightweight message telling the Android application
+<p>Google Cloud Messaging (GCM) is a free service that enables developers
+to send downstream messages (from servers to GCM-enabled client apps), and
+upstream messages (from the GCM-enabled client apps to servers).
+This could be a lightweight message telling the client app
that there is new data to be fetched from the server (for instance, a "new email"
-notification informing the application that it is out of sync with the back end),
+notification informing the app that it is out of sync with the back end),
or it could be a message containing up to 4kb of payload
data (so apps like instant messaging can consume the message directly). The GCM
-service handles all aspects of queueing of messages and delivery to the target
-Android application running on the target device.</p>
-
-<p class="note"> To jump right into using GCM with your Android
- applications, see <a href="gs.html">Getting Started</a>.</p>
+service handles all aspects of queueing of messages and delivery to and from
+the target client app.</p>
-<p>Here are the primary characteristics of Google Cloud
-Messaging (GCM):</p>
-
-<ul>
- <li>It allows 3rd-party application servers to send messages to
-their Android applications.</li>
- <li>Using the <a href="ccs.html">GCM Cloud Connection Server</a>, you can receive
-upstream messages from the user's device.</li>
- <li>An Android application on an Android device doesn't need to be running to receive
-messages. The system will wake up the Android application via Intent broadcast
-when the message arrives, as long as the application is set up with the proper
-broadcast receiver and permissions.</li>
- <li>It does not provide any built-in user interface or other handling for
-message data. GCM simply passes raw message data received straight to the
-Android application, which has full control of how to handle it. For example, the
-application might post a notification, display a custom user interface, or
-silently sync data.</li>
- <li>It requires devices running Android 2.2 or higher that also have the
-Google Play Store application installed, or or an emulator running Android 2.2
-with Google APIs. However, you are not limited to deploying your
-Android applications through Google Play Store.</li>
- <li>It uses an existing connection for Google services. For pre-3.0 devices,
-this requires users to
-set up their Google account on their mobile devices. A Google account is not a
-requirement on devices running Android 4.0.4 or higher.</li>
-</ul>
<h2 id="key">Key Concepts</h2>
@@ -70,7 +36,7 @@ divided into these categories:</p>
<li><strong>Components</strong> &mdash; The entities that play a primary role in
GCM.</li>
<li><strong>Credentials</strong> &mdash; The IDs and tokens that are used in
-different stages of GCM to ensure that all parties have been authenticated, and
+GCM to ensure that all parties have been authenticated, and
that the message is going to the correct place.</li>
</ul>
@@ -81,24 +47,20 @@ that the message is going to the correct place.</li>
<tr>
<th colspan="2">Components</th>
</tr>
- <tr>
- <td width="165"><strong>Client App</strong></td>
- <td width="1176">The GCM-enabled Android application that is running on a
- device. This must be a 2.2 Android device that has Google Play Store installed, and it must
-have at least one logged in Google account if the device is running a version
-lower than Android 4.0.4. Alternatively, for testing you can use an emulator
-running Android 2.2 with Google APIs.</td>
+<tr>
+ <td><strong>GCM Connection Servers</strong></td>
+ <td>The Google-provided servers involved in sending messages between the
+3rd-party app server and the client app.</td>
</tr>
<tr>
- <td><strong>3rd-party Application Server</strong></td>
- <td>An application server that you write as part of implementing
-GCM. The 3rd-party application server sends data to an
-Android application on the device via the GCM connection server.</td>
+ <td><strong>Client App</strong></td>
+ <td>A GCM-enabled client app that communicates with a 3rd-party app server.</td>
</tr>
<tr>
- <td><strong>GCM Connection Servers</strong></td>
- <td>The Google-provided servers involved in taking messages from the 3rd-party
-application server and sending them to the device. </td>
+ <td><strong>3rd-party App Server</strong></td>
+ <td>An app server that you write as part of implementing
+GCM. The 3rd-party app server sends data to a client app via
+the GCM connection server.</td>
</tr>
<tr>
<th colspan="2">Credentials</th>
@@ -108,43 +70,29 @@ application server and sending them to the device. </td>
<td>A project number you acquire from the API console, as described in
<a href="gs.html#create-proj">Getting Started</a>. The sender
ID is used in the <a href="#register">registration process</a> to identify a
-3rd-party application server that is permitted to send messages to the device.</td>
+3rd-party app server that is permitted to send messages to the client app.</td>
+ </tr>
+ <tr>
+ <td id="apikey"><strong>Sender Auth Token</strong></td>
+ <td>An API key that is saved on the 3rd-party app
+server that gives the app server authorized access to Google services.
+The API key is included in the header of POST requests.
+</td>
</tr>
<tr>
<td><strong>Application ID</strong></td>
- <td>The Android application that is registering to receive messages. The Android application
+ <td>The client app that is registering to receive messages. How this is implemented
+is platform-dependent. For example, an Android app
is identified by the package name from the <a href="client.html#manifest">manifest</a>.
-This ensures that the messages are targeted to the correct Android application.</td>
+This ensures that the messages are targeted to the correct Android app.</td>
</tr>
<tr>
<td><strong>Registration ID</strong></td>
- <td>An ID issued by the GCM servers to the Android application that allows
-it to receive messages. Once the Android application has the registration ID, it sends
-it to the 3rd-party application server, which uses it to identify each device
-that has registered to receive messages for a given Android application. In other words,
-a registration ID is tied to a particular Android application running on a particular
-device. Note that registration IDs must be kept secret.
-<br/>
-<br/>
-<strong>Note:</strong> If you use
-<a href="https://developer.android.com/google/backup/index.html">backup and restore</a>,
-you should explicitly avoid backing up registration IDs. When you back up
-a device, apps back up shared prefs indiscriminately. If you don't explicitly
-exclude the GCM registration ID, it could get reused on a new device,
-which would cause delivery errors.
+ <td>An ID issued by the GCM servers to the client app that allows
+it to receive messages. Note that registration IDs must be kept secret.
+
</td>
</tr>
- <tr>
- <td><strong>Google User Account</strong></td>
- <td>For GCM to work, the mobile device must include at least one Google
-account if the device is running a version lower than Android 4.0.4.</td>
- </tr>
- <tr>
- <td id="apikey"><strong>Sender Auth Token</strong></td>
- <td>An API key that is saved on the 3rd-party application
-server that gives the application server authorized access to Google services.
-The API key is included in the header of POST requests that send messages.</td>
- </tr>
</table>
@@ -152,7 +100,8 @@ The API key is included in the header of POST requests that send messages.</td>
<p>A GCM implementation includes a Google-provided
connection server, a 3rd-party app server that interacts with the connection
-server, and a GCM-enabled client app running on an Android device:</p>
+server, and a GCM-enabled client app. For example, this diagram shows GCM
+communicating with a client app on an Android device:</p>
<img src="{@docRoot}images/gcm/GCM-arch.png">
@@ -163,84 +112,196 @@ server, and a GCM-enabled client app running on an Android device:</p>
<p>This is how these components interact:</p>
<ul>
<li>Google-provided <strong>GCM Connection Servers</strong> take messages from
-a 3rd-party application server and send these messages to a
-GCM-enabled Android application (the &quot;client app&quot;) running on a device.
+a 3rd-party app server and send these messages to a
+GCM-enabled client app (the &quot;client app&quot;).
Currently Google provides connection servers for <a href="http.html">HTTP</a>
and <a href="ccs.html">XMPP</a>.</li>
- <li>The <strong>3rd-Party Application Server</strong> is a component that you
+ <li>The <strong>3rd-Party App Server</strong> is a component that you
implement to work with your chosen GCM connection server(s). App servers send
messages to a GCM connection server; the connection server enqueues and stores the
-message, and then sends it to the device when the device is online.
+message, and then sends it to the client app.
For more information, see <a href="server.html">Implementing GCM Server</a>.</li>
- <li>The <strong>Client App</strong> is a GCM-enabled Android application running
-on a device. To receive GCM messages, this app must register with GCM and get a
+ <li>The <strong>Client App</strong> is a GCM-enabled client app.
+To receive GCM messages, this app must register with GCM and get a
registration ID. If you are using the <a href="ccs.html">XMPP</a> (CCS) connection
-server, the client app can send "upstream" messages back to the connection server.
+server, the client app can send "upstream" messages back to the 3rd-party app server.
For more information on how to implement the client app, see
-<a href="client.html">Implementing GCM Client</a>.</li>
+the documentation for your platform.</li>
</ul>
<h2 id="lifecycle">Lifecycle Flow</h2>
<ul>
- <li><a href="#register">Enable GCM</a>. An Android application running on a
-mobile device registers to receive messages.</li>
+ <li><strong>Register to enable GCM</strong>. A client app registers to receive messages.
+For more discussion, see <a href="#register">Register to enable GCM</a>.</li>
+ <li><strong>Send and receive downstream messages</strong>.
+ <ul>
+ <li>Send a message. A 3rd-party app server sends messages to the client app:
+ <ol>
+ <li>The 3rd-party app server <a href="server.html#send-msg">sends a message</a>
+to GCM connection servers.</li>
+ <li>The GCM connection server enqueues and stores the message if the device is offline.</li>
+ <li>When the device is online, the GCM connection server sends the message to the device. </li>
+ <li>On the device, the client app receives the message according to the platform-specific implementation.
+See your platform-specific documentation for details.</li>
+ </ol>
+ </li>
+ <li>Receive a message. A client app
+receives a message from a GCM server. See your platform-specific documentation for details
+on how a client app in that environment processes the messages it receives.</li>
+ </ul>
+</li>
+
+ <li><strong>Send and receive upstream messages</strong>. This feature is only available if
+you're using the <a href="ccs.html">XMPP Cloud Connection Server</a> (CCS).
+<ul>
+ <li>Send a message. A client app sends messages to the 3rd-party app server:
+ <ol>
+ <li>On the device, the client app sends messages to XMPP (CCS).See your platform-specific
+ documentation for details on how a client app can send a message to XMPP (CCS).</li>
+ <li>XMPP (CCS) enqueues and stores the message if the server is disconnected.</li>
+ <li>When the 3rd-party app server is re-connected, XMPP (CCS) sends the message to the 3rd-party app server.</li>
+ </ol>
+ </li>
+ <li>Receive a message. A 3rd-party app server receives a message from XMPP (CCS) and then does the following:
+ <ol>
+ <li>Parses the message header to verify client app sender information.
+ <li>Sends "ack" to GCM XMPP connection server to acknowledge receiving the message.
+ <li>Optionally parses the message payload, as defined by the client app.
+ </ol>
+</li>
+</ul>
+
+</li>
+
- <li><a href="#push-process">Send a message</a>. A 3rd-party application
-server sends messages to the device.</li>
- <li><a href="#receiving">Receive a message</a>. An Android application
-receives a message from a GCM server.</li>
</ul>
-<p>These processes are described in more detail below.</p>
+<h2 id="reg">Register to enable GCM</h2>
+
+<p>Regardless of the platform you're developing on, the first step
+a client app must do is register with GCM. This section covers some of the general
+best practices for registration and unregistration. See your platform-specific docs for
+details on writing a GCM-enabled client app on that platform.</p>
-<h3 id="register">Enable GCM</h3>
+<h3 id="reg-state">Keeping the Registration State in Sync</h3>
+<p>Whenever the app registers as described in
+<a href="{@docRoot}google/gcm/client.html">Implementing GCM Client</a>,
+it should save the registration ID for future use, pass it to the
+3rd-party server to complete the registration, and keep track of
+whether the server completed the registration. If the server fails
+to complete the registration, the client app should retry passing the
+registration ID to 3rd-party app server to complete the registration.
+If this continues to fail, the client app should unregister from GCM.</p>
-<p>The first time the Android application needs to use the messaging service, it
-calls the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a> method {@code register()}, as discussed in
-<a href="client.html">Implementing GCM Client</a>.
-The {@code register()} method returns a registration ID. The Android
-application should store this ID for later use (for instance,
-to check in <code>onCreate()</code> if it is already registered).
+<p>There are also two other scenarios that require special care:</p>
+<ul>
+ <li>Client app update</li>
+ <li>Backup and restore
+ </li>
+</ul>
+<p><bold>Client app update:</bold> When a client app is updated, it should invalidate its existing registration
+ID, as it is not guaranteed to work with the new version. The recommended way to achieve
+this validation is by storing the current app version when a registration
+ID is stored. Then when the app starts, compare the stored value with
+the current app version. If they do not match, invalidate the stored data
+and start the registration process again.</p>
+
+<p><bold>Backup and restore: </bold> You should not save the registration ID when an app is
+backed up. This is because the registration ID could become invalid by the time
+the app is restored, which would put the app in an invalid state
+(that is, the app thinks it is registered, but the server and GCM do not
+store that registration ID anymore&mdash;thus the app will not get more
+messages). The best practice is to initiate the registration process as if the app has been
+installed for the first time.</p>
+
+<h4 id="canonical">Canonical IDs</h4>
+<p>If a bug in the app triggers multiple
+registrations for the same device, it can be hard to reconcile state and you might
+end up with duplicate messages.</p>
+<p>GCM provides a facility called &quot;canonical registration IDs&quot; to easily
+recover from these situations. A canonical registration ID is defined to be the ID
+of the last registration requested by your app. This is the ID that the
+server should use when sending messages to the device.</p>
+<p>If later on you try to send a message using a different registration ID, GCM
+will process the request as usual, but it will include the canonical registration
+ID in the <code>registration_id</code> field of the response. Make sure to replace
+the registration ID stored in your server with this canonical ID, as eventually
+the ID you're using will stop working.</p>
+
+<h3 id="retry">Automatic Retry Using Exponential Back-Off</h3>
+
+<p>When registration or unregistration fails, the app should retry the failed operation.</p>
+<p>In the simplest case, if your app attempts to register and GCM is not a
+fundamental part of the app, the app could simply ignore the error
+and try to register again the next time it starts. Otherwise, it should retry the
+previous operation using exponential back-off. In exponential back-off, each time
+there is a failure, it should wait twice the previous amount of time before trying
+again.
</p>
-<h3 id="push-process">Send a message</h3>
+<h3 id="unreg">Unregistration</h3>
-<p>Here is the sequence of events that occurs when the application server sends a
-message:</p>
+<p>This section explains when you should unregister in GCM and what happens
+when you do.</p>
-<ol>
- <li>The application server sends a message to GCM servers.</li>
- <li>Google enqueues and stores the message in case the device is
-offline.</li>
- <li>When the device is online, Google sends the message to the device. </li>
- <li>On the device, the system broadcasts the message to the specified
-Android application via Intent broadcast with proper permissions, so that only the
-targeted Android application gets the message. This wakes the Android application up. The
-Android application does not need to be running beforehand to receive the message.</li>
- <li>The Android application processes the message. If the Android application is doing
-non-trivial processing, you may want to grab a
-{@link android.os.PowerManager.WakeLock} and do any processing in a service.</li>
-</ol>
+<h4 id="unreg-why">Why you should rarely unregister</h4>
+
+<p>You should only need to unregister in rare cases, such as
+if you want an app to stop receiving messages, or if you suspect that the registration ID has
+been compromised. In general, once an app has a registration ID, you shouldn't need
+to change it.</p>
-<p> An Android application can unregister GCM if it no longer wants to receive
-messages.</p>
+<p>In particular, you should never unregister your app as a mechanism for
+logout or for switching between users, for the following reasons:</p>
+
+<ul>
+ <li>A registration ID isn't associated with a particular
+ logged in user. If you unregister and then re-register, GCM may return the same
+ ID or a different ID&mdash;there's no guarantee either way.</li>
+
+ <li>Unregistration may take up to 5 minutes to propagate.</li>
+ <li>After unregistration, re-registration may again take up to 5 minutes to
+propagate. During this time messages may be rejected due to the state of being
+unregistered, and after all this, messages may still go to the wrong user.</li>
+</ul>
-<h3 id="receiving">Receive a message</h3>
-<p>This is the sequence of events that occurs when an Android application
-installed on a mobile device receives a message:</p>
+<p>To make sure that messages go to the intended user:</p>
+<ul>
+ <li>Your app server can maintain a mapping between the current user
+and the registration ID.</li>
+ <li>The app can then check to ensure that messages it
+receives match the logged in user.</li>
+</ul>
+
+
+<h4 id="unreg-how">How unregistration works</h4>
+
+<p>An app can be automatically unregistered after it is uninstalled.
+However, this process does not happen right away. What happens in
+this scenario is as follows:</p>
<ol>
- <li>The system receives the incoming message and extracts the raw key/value
-pairs from the message payload, if any.</li>
- <li>The system passes the key/value pairs to the targeted Android application
-in a <code>com.google.android.c2dm.intent.RECEIVE</code> Intent as a set of
-extras.</li>
- <li>The Android application extracts the raw data
-from the <code>com.google.android.c2dm.intent.RECEIVE</code><code> </code>Intent
-by key and processes the data.</li>
+ <li>The end user uninstalls the client app.</li>
+ <li>The 3rd-party app server sends a message to GCM server.</li>
+ <li>The GCM server sends the message to the GCM client on the device.</li>
+ <li>The GCM client on the device receives the message and detects that the client app has been
+ uninstalled; the detection details depend on the platform on which the client app is running.
+</li>
+ <li>The GCM client on the device informs the GCM server that the client app was uninstalled.</li>
+ <li>The GCM server marks the registration ID for deletion.</li>
+ <li>The 3rd-party app server sends a message to GCM.</li>
+ <li>The GCM returns a <code>NotRegistered</code> error message to the 3rd-party app server.</li>
+ <li>The 3rd-party app server deletes the registration ID.
+ </li>
</ol>
+<p>Note that it might take a while for the registration ID be completely removed
+from GCM. Thus it is possible that messages sent during step 7 above gets a valid
+message ID as response, even though the message will not be delivered to the client app.
+Eventually, the registration ID will be removed and the server will get a
+<code>NotRegistered</code> error, without any further action being required from
+the 3rd-party server (this scenario happens frequently while an app is
+being developed and tested).</p>
diff --git a/docs/html/google/gcm/gs.jd b/docs/html/google/gcm/gs.jd
index a889624..2331292 100644
--- a/docs/html/google/gcm/gs.jd
+++ b/docs/html/google/gcm/gs.jd
@@ -1,4 +1,4 @@
-page.title=Getting Started
+page.title=Getting Started on Android
page.tags=cloud,push,messaging
@jd:body
@@ -46,7 +46,7 @@ project number. For example, <strong>Project Number: 670330094152</strong>.</p><
<li>Copy down your project number. You will use it later on as the
<a href="{@docRoot}google/gcm/gcm.html#senderid">GCM sender ID</a>.</li>
-
+
</ol>
<h2 id="gcm-service">Enabling the GCM Service</h2>
<p>To enable the GCM service:</p>
@@ -71,7 +71,7 @@ purposes, you can use {@code 0.0.0.0/0}.</p></li>
<li>In the refreshed page, copy the
<a href="{@docRoot}google/gcm/gcm.html#apikey">API key</a>.
-You will need the API key later on to perform authentication in your application server.</li>
+You will need the API key later on to perform authentication in your app server.</li>
<p class="note"><strong>Note:</strong> If you need to rotate the key, click
<strong>Regenerate key</strong>. A new key will be created. If you think the key has been
@@ -84,16 +84,11 @@ compromised and you want to delete it immediately, click <strong>Delete</strong>
implementing GCM. Here is an overview of the basic steps:</p>
<ol>
- <li>Decide which Google-provided GCM connection server you want to use&mdash;
- <a href="http.html">HTTP</a> or <a href="ccs.html">XMPP</a> (CCS). GCM connection servers
-take messages from a 3rd-party application
-server (written by you) and send them to a GCM-enabled Android application (the
-"client app," also written by you) running on a device. </li>
- <li>Implement an application server (the "3rd-party application server") to interact
+ <li>Implement an app server (the "3rd-party app server") to interact
with your chosen GCM connection server. The app server sends data to a
-GCM-enabled Android client application via the GCM connection server. For more
+GCM-enabled Android client app via the GCM connection server. For more
information about implementing the server side, see <a href="server.html">
Implementing GCM Server</a>.</li>
-<li>Write your client app. This is the GCM-enabled Android application that runs
+<li>Write your client app. This is the GCM-enabled Android app that runs
on a device. See <a href="client.html">Implementing GCM Client</a> for more information.</li>
</ol>
diff --git a/docs/html/google/gcm/http.jd b/docs/html/google/gcm/http.jd
index 773acd1..5022e09 100644
--- a/docs/html/google/gcm/http.jd
+++ b/docs/html/google/gcm/http.jd
@@ -23,6 +23,7 @@ page.title=GCM HTTP Connection Server
<h2>See Also</h2>
<ol class="toc">
+<li><a href="server-ref.html">Server Reference</a></li>
<li><a href="gs.html">Getting Started</a></li>
<li><a href="client.html">Implementing GCM Client</a></li>
<li><a href="ccs.html">Cloud Connection Server</a></li>
@@ -42,26 +43,30 @@ application server and sending them to the device.</p>
applies to <a href="http://developer.chrome.com/apps/cloudMessaging">
GCM with Chrome apps</a> as well as Android.</p>
-<p>See
-<a href="server.html#params">Implementing GCM Server</a> for a list of all the message
+<p>See the
+<a href="server-ref.html">Server Reference</a> for a list of all the message
parameters and which connection server(s) supports them.</p>
<h2 id="auth">Authentication</h2>
-<p>To send a message, the application server issues a POST request to
-<code>https://android.googleapis.com/gcm/send</code>.</p>
+<p>To send a message, the application server issues a POST request. For example:</p>
+<pre>https://android.googleapis.com/gcm/send</pre>
<p>A message request is made of 2 parts: HTTP header and HTTP body.</p>
<p>The HTTP header must contain the following headers:</p>
<ul>
<li><code>Authorization</code>: key=YOUR_API_KEY</li>
- <li><code>Content-Type</code>: <code>application/json</code> for JSON; <code>application/x-www-form-urlencoded;charset=UTF-8</code> for plain text.
+ <li><code>Content-Type</code>: <code>application/json</code> for JSON;
+<code>application/x-www-form-urlencoded;charset=UTF-8</code> for plain text.
+If <code>Content-Type</code> is omitted, the format
+is assumed to be plain text.
</li>
</ul>
<p>For example:
</p>
+
<pre>Content-Type:application/json
Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
@@ -71,26 +76,30 @@ Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
...
},
}</pre>
-<p class="note">
- <p><strong>Note:</strong> If <code>Content-Type</code> is omitted, the format
-is assumed to be plain text.</p>
-</p>
+
<p>The HTTP body content depends on whether you're using JSON or plain text.
See
-<a href="server.html#params">Implementing GCM Server</a> for a list of all the
+<a href="server-ref.html#params">the Server Reference</a> for a list of all the
parameters your JSON or plain text message can contain.</p>
<h2 id="request">Request Format</h2>
+
+<p>This section shows you how to format a request for both JSON and plain text. See
+the <a href="server-ref.html#table1">Server Reference</a> for a complete
+list of the fields you can include in a request.</p>
+
<p>Here is the smallest possible request (a message without any parameters and
just one recipient) using JSON:</p>
+
<pre class="prettyprint pretty-json">{ &quot;registration_ids&quot;: [ &quot;42&quot; ] }</pre>
<p>And here the same example using plain text:</p>
<pre class="prettyprint">registration_id=42</pre>
<p> Here is a message with a payload and 6 recipients:</p>
+
<pre class="prettyprint pretty-HTML">{ "data": {
"score": "5x1",
"time": "15:10"
@@ -112,10 +121,25 @@ just one recipient) using JSON:</p>
<pre class="prettyprint">collapse_key=score_update&amp;time_to_live=108&amp;delay_while_idle=1&amp;data.score=4x8&amp;data.time=15:16.2342&amp;registration_id=42
</pre>
+<p>Here is a message that includes a notification key and payload:</p>
+
+<pre>
+{
+ "data": {
+ "message": "ciao"
+ },
+ "notification_key":"aUniqueKey"
+}
+</pre>
+
+<p>For more information about notifications and how to use them, see
+<a href="{@docRoot}google/gcm/notifications.html">User Notifications</a>.</p>
+
+
<p class="note"><strong>Note:</strong> If your organization has a firewall
that restricts the traffic to or
from the Internet, you need to configure it to allow connectivity with GCM in order for
-your Android devices to receive messages.
+your GCM client apps to receive messages.
The ports to open are: 5228, 5229, and 5230. GCM typically only uses 5228, but
it sometimes uses 5229 and 5230. GCM doesn't provide specific IPs, so you should allow
your firewall to accept outgoing connections to all IP addresses
@@ -127,54 +151,12 @@ contained in the IP blocks listed in Google's ASN of 15169.</p>
<p>There are two possible outcomes when trying to send a message:</p>
<ul>
- <li>The message is processed successfully.</li>
- <li>The GCM server rejects the request.</li>
+ <li>The message is processed successfully. The HTTP response has a 200 status, and
+the body contains more information about the status of the message (including possible errors).</li>
+ <li>The GCM server rejects the request. The HTTP response contains a
+non-200 status code (such as 400, 401 or 5xx).</li>
</ul>
-<p>When the message is processed successfully, the HTTP response has a 200 status
-and the body contains more information about the status of the message
-(including possible errors). When the request is rejected,
-the HTTP response contains a non-200 status code (such as 400, 401, or 503).</p>
-
-<p>The following table summarizes the statuses that the HTTP response header might
-contain. Click the troubleshoot link for advice on how to deal with each type of
-error.</p>
-<table border=1>
- <tr>
- <th>Response</th>
- <th>Description</th>
- </tr>
- <tr>
- <td>200</td>
- <td>Message was processed successfully. The response body will contain more
-details about the message status, but its format will depend whether the request
-was JSON or plain text. See <a href="#success">Interpreting a success response</a>
-for more details.</td>
- </tr>
- <tr>
- <td>400</td>
- <td><span id="internal-source-marker_0.2">Only applies for JSON requests.
-Indicates that the request could not be parsed as JSON, or it contained invalid
-fields (for instance, passing a string where a number was expected). The exact
-failure reason is described in the response and the problem should be addressed
-before the request can be retried.</td>
- </tr>
- <tr>
- <td>401</td>
- <td>There was an error authenticating the sender account.
-<a href="#auth_error">Troubleshoot</a></td>
- </tr>
- <tr>
- <td>5xx</td>
- <td>Errors in the 500-599 range (such as 500 or 503) indicate that there was
-an internal error in the GCM server while trying to process the request, or that
-the server is temporarily unavailable (for example, because of timeouts). Sender
-must retry later, honoring any <code>Retry-After</code> header included in the
-response. Application servers must implement exponential back-off.
-<a href="#internal_error">Troubleshoot</a></td>
- </tr>
-</table>
-
<h3 id="success">Interpreting a success response</h3>
<p>When a JSON request is successful (HTTP status code 200), the response body
contains a JSON object with the following fields:</p>
@@ -241,8 +223,8 @@ code>registration_ids</code> passed in the request (using the same index).</li>
request.</li>
<li>If it is <code>NotRegistered</code>, you should remove the registration
ID from your server database because the application was uninstalled from the
-device or it does not have a broadcast receiver configured to receive
-<code>com.google.android.c2dm.intent.RECEIVE</code> intents.</li>
+device, or the client app isn't configured to receive
+messages.</li>
<li>Otherwise, there is something wrong in the registration ID passed in
the request; it is probably a non-recoverable error that will also require removing
the registration from the server database. See <a href="#error_codes">Interpreting
@@ -291,8 +273,7 @@ might occur when trying to send a message to a device:</p>
<dt id="invalid_reg"><strong>Invalid Registration ID</strong></dt>
<dd>Check the formatting of the registration ID that you pass to the server. Make
-sure it matches the registration ID the phone receives in the
-<code>com.google.android.c2dm.intent.REGISTRATION</code> intent and that you're
+sure it matches the registration ID the client app receives and that you're
not truncating it or adding additional characters.
<br/>Happens when error code is <code>InvalidRegistration</code>.</dd>
@@ -306,17 +287,13 @@ Happens when error code is <code>MismatchSenderId</code>.</dd>
<dt id="unreg_device"><strong>Unregistered Device</strong></dt>
<dd>An existing registration ID may cease to be valid in a number of scenarios, including:
<ul>
- <li>If the application manually unregisters by issuing a
-<span class="prettyprint pretty-java">
-<code>com.google.android.c2dm.intent.UNREGISTER</code></span><code>
-</code>intent.</li>
+ <li>If the application manually unregisters.</li>
<li>If the application is automatically unregistered, which can happen
(but is not guaranteed) if the user uninstalls the application.</li>
<li>If the registration ID expires. Google might decide to refresh registration
IDs. </li>
- <li>If the application is updated but the new version does not have a broadcast
-receiver configured to receive <code>com.google.android.c2dm.intent.RECEIVE</code>
-intents.</li>
+ <li>If the application is updated but the new version is not configured to receive
+messages.</li>
</ul>
For all these cases, you should remove this registration ID from the 3rd-party
server and stop using it to send
@@ -331,8 +308,7 @@ as the values.
<dt id="invalid_datakey"><strong>Invalid Data Key</strong></dt>
<dd>The payload data contains a key (such as <code>from</code> or any value
-prefixed by <code>google.</code>) that is used internally by GCM in the
-<code>com.google.android.c2dm.intent.RECEIVE</code> Intent and cannot be used.
+prefixed by <code>google.</code>) that is used internally by GCM and therefore cannot be used.
Note that some words (such as <code>collapse_key</code>) are also used by GCM
but are allowed in the payload, in which case the payload value will be
overridden by the GCM value.
@@ -354,9 +330,9 @@ authenticated. Possible causes are: <ul>
<li>Request originated from a server not whitelisted in the Server Key IPs.</li>
</ul>
-Check that the token you're sending inside the <code>Authorization</code> header
-is the correct API key associated with your project. You can check the validity
-of your API key by running the following command:<br/>
+When there is an Authentication Error, you can check the validity of your API key by running You can check the validity
+of your API key by running the following command (this example shows what you
+would do on Android; see the documentation for your platform):<br/>
<pre># api_key=YOUR_API_KEY
@@ -405,8 +381,7 @@ Happens when the HTTP status code is between 501 and 599, or when the
<dd>
The server encountered an error while trying to process the request. You
could retry the same request (obeying the requirements listed in the <a href="#timeout">Timeout</a>
-section), but if the error persists, please report the problem in the
-<a href="https://groups.google.com/forum/?fromgroups#!forum/android-gcm">android-gcm group</a>.
+section), but if the error persists, please report the problem to Google.
<br />
Happens when the HTTP status code is 500, or when the <code>error</code> field of a JSON
object in the results array is <code>InternalServerError</code>.
@@ -488,7 +463,7 @@ registration_id=32
<p>This section gives examples of implementing an app server that works with the
GCM HTTP connection server. Note that a full GCM implementation requires a
-client-side implementation, in addition to the server.</a>
+client-side implementation, in addition to the server. This example is based on Android.</a>
<p>Requirements</p>
@@ -508,7 +483,7 @@ version 1.6 or later.</li>
</ul>
<p>For the Android application:</p>
<ul>
- <li>Emulator (or device) running Android 2.2 with Google APIs.</li>
+ <li>Emulator (or device) running Android 2.2 (ideally, 2.3 or above) with Google APIs.</li>
<li>The Google API project number of the account registered to use GCM.</li>
</ul>
diff --git a/docs/html/google/gcm/notifications.jd b/docs/html/google/gcm/notifications.jd
index 147b69c..333d4b6 100644
--- a/docs/html/google/gcm/notifications.jd
+++ b/docs/html/google/gcm/notifications.jd
@@ -306,9 +306,3 @@ receive the message:</p>
<p>In the case of failure, the response has HTTP code 503 and no JSON. When a message
fails to be delivered to one or more of the regIDs associated with a {@code notification_key},
the 3rd-party server should retry.</p>
-
-
-
-
-
-
diff --git a/docs/html/google/gcm/server-ref.jd b/docs/html/google/gcm/server-ref.jd
new file mode 100644
index 0000000..a94e727
--- /dev/null
+++ b/docs/html/google/gcm/server-ref.jd
@@ -0,0 +1,763 @@
+page.title=Server Reference
+@jd:body
+
+<div id="qv-wrapper">
+<div id="qv">
+
+<h2>In this document</h2>
+
+<ol class="toc">
+ <li><a href="#downstream">Downstream Messages</a></li>
+<ol class="toc">
+ <li><a href="#send-downstream">Sending a downstream message</a></li>
+ <li><a href="#interpret-downstream">Interpreting a downstream message response</a></li>
+ </ol>
+ <li><a href="#upstream">Upstream Messages (XMPP)</a>
+ <ol class="toc">
+ <li><a href="#interpret-upstream">Interpreting an upstream XMPP message</a></li>
+ <li><a href="#upstream-response">Sending an upstream XMPP message response</a></li>
+ </ol>
+ </li>
+<li><a href="#ccs">Cloud Connection Server Messages (XMPP)</a></li>
+<li><a href="#error-codes">Downstream message error response codes (HTTP and XMPP)</a></li>
+</ol>
+
+</div>
+</div>
+
+<p>This document provides a reference for the syntax used to pass
+messages back and forth in GCM. These messages fall into
+the following broad categories:</p>
+
+<ul>
+ <li><a href="#downstream">Downstream messages</a></li>
+ <li><a href="#upstream">Upstream messages</a></li>
+ <li><a href="#ccs">Cloud Connection Server messages (XMPP)</a></li>
+ <li><a href="#error-codes">Downstream message error response codes (HTTP and XMPP)</a></li>
+</ul>
+
+<p>The following sections describe the basic requirements for
+sending messages.</p>
+
+<h2 id="downstream">Downstream Messages</h2>
+<p>This is the message that a 3rd-party app server sends to a client app.
+</p>
+<p>A downstream message includes the following components:</p>
+<ul>
+ <li>Target: specifies the recipient of the message.</li>
+ <li>Options: specifies attributes of the message.</li>
+ <li>Payload: specifies additional content to be included in the message. Optional.</li>
+</ul>
+
+<p>The syntax for each of these components is described in the tables below. </p>
+
+<h3 id="send-downstream">Sending a downstream message</h3>
+
+<p>This section gives the syntax for sending a downstream messages. For JSON,
+these messages can be either HTTP or XMPP. For plain text, these messages can only be HTTP.</p>
+
+<h4>Downstream HTTP or XMPP messages (JSON)</h4>
+
+<p>The following table lists the targets, options, and payload for HTTP or XMPP JSON messages.</p>
+<p class="table-caption" id="table1">
+ <strong>Table 1.</strong> Targets, options, and payload for downstream HTTP or XMPP message (JSON).</p>
+<table border="1">
+ <tr>
+ <th>Parameter</th>
+ <th>Protocol</th>
+ <th>Usage</th>
+ <th>Description</th>
+ </tr>
+<tr>
+ <td colspan="4"><strong>Targets</strong></td>
+ </tr>
+ <tr>
+ <td><code>to</code></td>
+ <td>XMPP</td>
+ <td>Required, string</td>
+ <td><p>This parameter specifies the recipient of a message. </p>
+ <p>The value must be a registration ID or notification key.</p>
+ <p>This parameter is used in XMPP in place of {@code registration_ids} or {@code notification_key} in HTTP.</p></td>
+ </tr>
+ <tr>
+ <td><code>registration_ids</code></td>
+ <td>HTTP</td>
+ <td>Required if {@code notification_key} not present, string array</td>
+ <td><p>This parameter specifies the list of devices (registration IDs)
+receiving the message. It must contain at least 1 and at most 1000 registration IDs.</p>
+ <p>Multicast messages (sending to more than 1 registration IDs) are allowed using HTTP JSON format only.</p>
+ <p>This parameter or {@code notification_key} is used in HTTP in place of {@code to} in XMPP.</p></td>
+ </tr>
+ <tr>
+ <td><code>notification_key</code></td>
+ <td>HTTP</td>
+ <td>Required if {@code registration_ids} not present, string</td>
+ <td><p>This parameter specifies the mapping of a single user to
+multiple registration IDs associated with that user.</p>
+ <p>This allows a 3rd-party app server to send a single message to multiple app instances
+(typically on multiple devices) owned by a single user.</p>
+ <p>A 3rd-party app server can use {@code notification_key} as the target for a
+message instead of an individual registration ID (or array of registration IDs).
+The maximum number of members allowed for a {@code notification_key} is 20.</p>
+ <p>This parameter or {@code registration_ids} is used in HTTP in place of {@code to} in XMPP.</p>
+ <p>See <a href="notifications.html">User Notifications</a> for details.</p></td>
+ </tr>
+<tr>
+ <td colspan="4"><strong>Options</strong></td>
+ </tr>
+ <tr>
+ <td><code>message_id</code></td>
+ <td>XMPP</td>
+ <td>Required, string</td>
+ <td><p>This parameter uniquely identifies a message in an XMPP connection.</p></td>
+ </tr>
+ <tr>
+ <td><code>collapse_key</code></td>
+ <td>HTTP, XMPP</td>
+ <td>Optional, string</td>
+ <td><p>This parameters identifies a group of messages (e.g., with
+{@code collapse_key: "Updates Available"}) that can be collapsed, so that only the
+last message gets sent when delivery can be resumed. This is intended to avoid sending too
+many of the same messages when the device comes back online or becomes active (see {@code delay_while_idle}).</p>
+ <p>Note that there is no guarantee of the order in which messages get sent.</p>
+ <p>Messages with collapse key are also called
+<a href="{@docRoot}google/gcm/server.html#s2s">send-to-sync messages</a> messages.
+</p>
+ <p>Note: A maximum of 4 different collapse keys is allowed at any given time. This means a
+GCM connection server can simultaneously store 4 different send-to-sync messages per client app. If you
+exceed this number, there is no guarantee which 4 collapse keys the GCM connection server will keep. </p></td>
+ </tr>
+ <tr>
+ <td><code>delay_while_idle</code></td>
+ <td>HTTP, XMPP</td>
+ <td>Optional, JSON boolean</td>
+ <td>When this parameter is set to {@code true}, it indicates that the message should not be
+sent until the device becomes active.</p>
+ <p>The default value is {@code false}.</p></td>
+ </tr>
+ <tr>
+ <td><code>time_to_live</code></td>
+ <td>HTTP, XMPP</td>
+ <td>Optional, JSON number</td>
+ <td><p>This parameter specifies how long (in seconds) the message should be kept in GCM storage
+if the device is offline. The maximum time to live supported is 4 weeks.</p>
+ <p>The default value is 4 weeks. </p></td>
+ </tr>
+ <tr>
+ <td><code>delivery_receipt_
+<br>requested</code></td>
+ <td>XMPP</td>
+ <td>Optional, JSON boolean</td>
+ <td><p>This parameter lets 3rd-party app server request confirmation of message delivery.</p>
+ <p>When this parameter is set to {@code true}, CCS sends a delivery receipt
+when the device confirms that it received the message.</p>
+ <p>The default value is {@code false}.</p></td>
+ </tr>
+ <tr>
+ <td><code>restricted_package_
+<br>name</code></td>
+ <td>HTTP</td>
+ <td>Optional, string</td>
+ <td>This parameter specifies the package name of the application where the
+registration IDs must match in order to receive the message.</td>
+ </tr>
+ <tr>
+ <td><code>dry_run</code></td>
+ <td>HTTP</td>
+ <td>Optional, JSON boolean</td>
+ <td><p>This parameter, when set to {@code true}, allows developers to test a
+request without actually sending a message.</p>
+ <p>The default value is {@code false}.</p></td>
+ </tr>
+<tr>
+ <td colspan="4"><strong>Payload</strong></td>
+ </tr>
+ <tr>
+ <td><code>data</code></td>
+ <td>HTTP, XMPP</td>
+ <td>Optional, JSON object</td>
+ <td><p>This parameter specifies the key-value pairs of the message's payload. There is
+no limit on the number of key-value pairs, but there is a total message size limit of 4kb.</p>
+ <p>For instance, in Android, <code>data:{"score":"3x1"}</code> would result in an intent extra
+named {@code score} with the string value {@code 3x1}.</p>
+ <p>The key should not be a reserved word ({@code from} or any word starting with
+{@code google}). It is also not recommended to use words defined in this table
+(such as {@code collapse_key}) because that could yield unpredictable outcomes. </p>
+ <p>Values in string types are recommended. You have to convert values in objects
+or other non-string data types (e.g., integers or booleans) to string.</p></td>
+ </tr>
+</table>
+
+<h3>Downstream HTTP messages (Plain Text)</h3>
+
+<p>The following table lists the syntax for targets, options, and payload in plain
+text downstream HTTP messages.</p>
+
+<p class="table-caption" id="table2">
+ <strong>Table 2.</strong> Targets, options, and payload for downstream plain text HTTP messages.</p>
+
+<table border="1">
+ <tr>
+ <th>Parameter</th>
+ <th>Usage</th>
+ <th>Description</th>
+ </tr>
+<tr>
+ <td colspan="3"><strong>Targets</strong></td>
+ </tr>
+ <tr>
+ <td><code>registration _id</code></td>
+ <td>Required, string</td>
+ <td><p>This parameter specifies the client apps (registration ID) receiving the message.</p>
+ <p>Multicast messaging (sending to more than one registration ID) is allowed using HTTP JSON format only.</p></td>
+ </tr>
+<tr>
+ <td colspan="3"><strong>Options</strong></td>
+ </tr>
+ <tr>
+ <td><code>collapse_key</code></td>
+ <td>Optional, string</td>
+ <td>See <a href="#table1">table 1</a> for details.</td>
+ </tr>
+ <tr>
+ <td><code>delay_while_idle</code></td>
+ <td>Optional, boolean or number</td>
+ <td>See <a href="#table1">table 1</a> for details.</td>
+ </tr>
+ <tr>
+ <td><code>time_to_live</code></td>
+ <td>Optional, number</td>
+ <td>See <a href="#table1">table 1</a> for details.</td>
+ </tr>
+ <tr>
+ <td><code>restricted_package_name</code></td>
+ <td>Optional, string</td>
+ <td>See <a href="#table1">table 1</a> for details.</td>
+ </tr>
+ <tr>
+ <td><code>dry_run </code></td>
+ <td>Optional, boolean</td>
+ <td>See <a href="#table1">table 1</a> for details.</td>
+ </tr>
+<tr>
+ <td colspan="3"><strong>Payload</strong></td>
+ </tr>
+ <tr>
+ <td><code>data.&lt;key&gt;</code></td>
+ <td>Optional, string</td>
+ <td><p>This parameter specifies the key-value pairs of the message's payload.
+There is no limit on the number of key-value parameters,
+but there is a total message size limit of 4kb.</p>
+ <p>For instance, in Android, <code>data:{"score":"3x1"}</code> would result in an intent extra
+named {@code score} with the string value {@code 3x1}.</p>
+ <p>The key should not be a reserved word ({@code from} or any word starting with
+{@code google}). It is also not recommended to use words defined in this table
+(such as {@code collapse_key}) because that could yield unpredictable outcomes.</p></td>
+ </tr>
+</table>
+
+<h3 id="interpret-downstream">Interpreting a Downstream Message Response</h3>
+
+<p>This section describes the syntax of a response to a downstream message. A client
+app or the GCM Connection Server sends the response to 3rd-party app server upon processing
+the message request. </p>
+
+<h4>Interpreting a downstream HTTP message response </h4>
+<p>The 3rd-party app server should look at both the message response header and the body
+to interpret the message response sent from the GCM Connection Server. The following table
+describes the possible responses.</p>
+<p>
+
+<p class="table-caption" id="table3">
+ <strong>Table 3.</strong> Downstream HTTP message response header.</p>
+<table border=1>
+ <tr>
+ <th>Response</th>
+ <th>Description</th>
+ </tr>
+ <tr>
+ <td>200</td>
+ <td>Message was processed successfully. The response body will contain more
+details about the message status, but its format will depend whether the request
+was JSON or plain text. See <a href="#table4">table 4</a>
+for more details.</td>
+ </tr>
+ <tr>
+ <td>400</td>
+ <td>Only applies for JSON requests.
+Indicates that the request could not be parsed as JSON, or it contained invalid
+fields (for instance, passing a string where a number was expected). The exact
+failure reason is described in the response and the problem should be addressed
+before the request can be retried.</td>
+ </tr>
+ <tr>
+ <td>401</td>
+ <td>There was an error authenticating the sender account.
+<a href="server.html#auth_error">Troubleshoot</a></td>
+ </tr>
+ <tr>
+ <td>5xx</td>
+ <td>Errors in the 500-599 range (such as 500 or 503) indicate that there was
+an internal error in the GCM server while trying to process the request, or that
+the server is temporarily unavailable (for example, because of timeouts). Sender
+must retry later, honoring any <code>Retry-After</code> header included in the
+response. Application servers must implement exponential back-off.
+<a href="server.html#internal_error">Troubleshoot</a></td>
+ </tr>
+</table>
+
+<p>The following table lists the fields in a downstream message response body
+(JSON).</p>
+
+
+<p class="table-caption" id="table4">
+ <strong>Table 4.</strong> Downstream HTTP message response body (JSON).</p>
+<table>
+ <tr>
+ <th>Parameter</th>
+ <th>Usage</th>
+ <th>Description</th>
+ </tr>
+ <tr>
+ <td><code>multicast_id</code></td>
+ <td>Required, number</td>
+ <td>Unique ID (number) identifying the multicast message.</td>
+ </tr>
+ <tr>
+ <td><code>success</code></td>
+ <td>Required, number</td>
+ <td>Number of messages that were processed without an error.</td>
+ </tr>
+ <tr>
+ <td><code>failure</code></td>
+ <td>Required, number</td>
+ <td>Number of messages that could not be processed.</td>
+ </tr>
+ <tr>
+ <td><code>canonical_ids</code></td>
+ <td>Required, number</td>
+ <td>Number of results that contain a canonical registration ID. See the
+<a href="{@docRoot}google/gcm/gcm.html#canonical">Overview</a> for more discussion of this topic.</td>
+ </tr>
+ <tr>
+ <td><code>results</code></td>
+ <td>Optional, array object</td>
+ <td>Array of objects representing the status of the messages processed. The
+objects are listed in the same order as the request (i.e., for each registration
+ID in the request, its result is listed in the same index in the response).<br>
+ <ul>
+ <li><code>message_id</code>: String specifying a unique ID for each successfully processed
+ message.</li>
+ <li><code>registration_id</code>: Optional string specifying the canonical registration ID
+ for the client app that the message was processed and sent to. Sender should use this
+ value as the Registration ID for future requests. Otherwise, the messages might
+ be rejected.
+ </li>
+ <li><code>error</code>: String specifying the error that occurred when processing the
+ message for the recipient. The possible values can be found in <a href="#table11">table 11
+ </a>.</li>
+ </ul></td>
+ </tr>
+</table>
+
+
+<p class="table-caption" id="table5">
+ <strong>Table 5.</strong> Success response for downstream HTTP message response body (Plain Text).</p>
+<table border="1">
+ <tr>
+ <th>Parameter</th>
+ <th>Usage</th>
+ <th>Description</th>
+ </tr>
+ <tr>
+ <td><code>id</code></td>
+ <td>Required, string</td>
+ <td>This parameter specifies the unique message ID that GCM server processed successfully.</td>
+ </tr>
+ <tr>
+ <td><code>registration_id</code></td>
+ <td>Optional, string</td>
+ <td>This parameter specifies the canonical registration ID for the client app that the message was
+processed and sent to. Sender should replace the registration ID with this value on future requests,
+otherwise, the messages might be rejected.</td>
+ </tr>
+</table>
+
+<p class="table-caption" id="table6">
+ <strong>Table 6.</strong> Error response for downstream HTTP message response body (Plain Text).</p>
+<table border="1">
+ <tr>
+ <th>Parameter</th>
+ <th>Usage</th>
+ <th>Description</th>
+ </tr>
+ <tr>
+ <td>{@code Error}</td>
+ <td>Required, string</td>
+ <td>This parameter specifies the error value while processing the message for the recipient.
+See <a href="#table11">table 11</a> for details. </td>
+ </tr>
+</table>
+
+<h4>Interpreting a downstream XMPP message response</h4>
+
+<p>The following table lists the fields that appear in a downstream XMPP message response.</p>
+
+<p class="table-caption" id="table7">
+ <strong>Table 7.</strong> Downstream message XMPP message response body.</p>
+<table border="1">
+ <tr>
+ <th>Parameter</th>
+ <th>Usage</th>
+ <th>Description</th>
+ </tr>
+ <tr>
+ <td><code>from</code></td>
+ <td>Required, string</td>
+ <td><p>This parameter specifies who sent this response.</p>
+ <p>The value is the registration ID of the client app.</p></td>
+ </tr>
+ <tr>
+ <td><code>message_id</code></td>
+ <td>Required, string</td>
+ <td>This parameter uniquely identifies a message in an XMPP connection.
+The value is a string that uniquely identifies the associated message.</td>
+ </tr>
+ <tr>
+ <td><code>message_type</code></td>
+ <td>Required, string</td>
+ <td><p>This parameter specifies an 'ack' or 'nack' message from XMPP (CCS)
+to the 3rd-party app server.</p>
+ <p>If the value is set to {@code nack}, the 3rd-party app server should look at
+{@code error} and {@code error_description} to get failure information. </p></td>
+ </tr>
+ <tr>
+ <td><code>error</code></td>
+ <td>Optional, string</td>
+ <td>This parameter specifies an error related to the downstream message. It is set when the
+{@code message_type} is {@code nack}. See <a href="#table11">table 6</a> for details.</td>
+ </tr>
+ <tr>
+ <td><code>error_description</code></td>
+ <td>Optional, string</td>
+ <td>This parameter provides descriptive information for the error. It is set
+when the {@code message_type} is {@code nack}.</td>
+ </tr>
+</table>
+<h2 id="upstream">Upstream Messages (XMPP)</h2>
+
+<p>An upstream message is a message the client app sends to the 3rd-party app server.
+Currently only CCS (XMPP) supports upstream messaging.</p>
+
+<h3 id="interpret-upstream">Interpreting an upstream XMPP message </h3>
+<p>The following table describes the fields that appear in an upstream XMPP message.
+
+<p class="table-caption" id="table8">
+ <strong>Table 8.</strong> Upstream XMPP messages.</p>
+<table border="1">
+ <tr>
+ <th>Parameter</th>
+ <th>Usage</th>
+ <th>Description</th>
+ </tr>
+ <tr>
+ <td><code>from</code></td>
+ <td>Required, string</td>
+ <td><p>This parameter specifies who sent the message.</p>
+ <p>The value is the registration ID of the client app.</p></td>
+ </tr>
+ <tr>
+ <td><code>category</code></td>
+ <td>Required, string</td>
+ <td>This parameter specifies the application package name of the client app that sent the message. </td>
+ </tr>
+ <tr>
+ <td><code>message_id</code></td>
+ <td>Required, string</td>
+ <td>This parameter specifies the unique ID of the message. </td>
+ </tr>
+ <tr>
+ <td><code>data</code></td>
+ <td>Optional, string</td>
+ <td>This parameter specifies the key-value pairs of the message's payload.</td>
+ </tr>
+</table>
+
+<h3 id="upstream-response">Sending an upstream XMPP message response</h3>
+
+<p>The following table describes the response that 3rd-party app server is expected to send to
+<a href="{@docRoot}google/gcm/ccs.html">XMPP (CCS)</a> in response to an
+upstream message it (the app server) received.</p>
+
+<p class="table-caption" id="table9">
+ <strong>Table 9.</strong> Upstream XMPP message response.</p>
+<table border="1">
+ <tr>
+ <th>Parameter</th>
+ <th>Usage</th>
+ <th>Description</th>
+ </tr>
+ <tr>
+ <td><code>to</code></td>
+ <td>Required, string</td>
+ <td><p>This parameter specifies the recipient of a response message. </p>
+ <p>The value must be a registration ID of the client app that sent the upstream message.</p></td>
+ </tr>
+ <tr>
+ <td><code>message_id</code></td>
+ <td>Required, string</td>
+ <td>This parameter specifies which message the response is intended for. The value must be
+the {@code message_id} value from the corresponding upstream message.</td>
+ </tr>
+ <tr>
+ <td><code>message_type</code></td>
+ <td>Required, string</td>
+ <td>This parameter specifies an {@code ack} message from a 3rd-party app server to CCS.</td>
+ </tr>
+</table>
+<h2 id="ccs">Cloud Connection Server Messages (XMPP) </h2>
+<p>This is a message sent from XMPP (CCS) to a 3rd-party app server. Here are the primary types
+of messages that XMPP (CCS) sends to the 3rd-party app server:</p>
+<ul>
+ <li><strong>Delivery Receipt:</strong> If the 3rd-party app server included {@code delivery_receipt_requested}
+in the downstream message, XMPP (CCS) sends a delivery receipt when it receives confirmation
+that the device received the message.</li>
+ <li><strong>Control:</strong> These CCS-generated messages indicate that
+action is required from the 3rd-party app server.</li>
+</ul>
+
+<p>The following table describes the fields included in the messages CCS
+sends to a 3rd-party app server.</p>
+
+<p class="table-caption" id="table10">
+ <strong>Table 10.</strong> GCM Cloud Connection Server messages (XMPP).</p>
+<table border="1">
+ <tr>
+ <th>Parameter</th>
+ <th>Usage</th>
+ <th>Description</th>
+ </tr>
+ <tr>
+ <td colspan="3"><strong>Common Field</strong></td>
+ </tr>
+ <tr>
+ <td><code>message_type</code></td>
+ <td>Required, string</td>
+ <td><p>This parameter specifies the type of the CCS message: either delivery receipt or control.</p>
+ <p>When it is set to {@code receipt}, the message includes {@code from}, {@code message_id},
+ {@code category} and {@code data} fields to provide additional information.</p>
+ <p>When it is set to {@code control}, the message includes {@code control_type} to indicate the
+type of control message.</p></td>
+ </tr>
+ <tr>
+ <td colspan="3"><strong>Delivery receipt-specific</strong></td>
+ </tr>
+ <tr>
+ <td><code>from</code></td>
+ <td>Required, string</td>
+ <td>This parameter is set to {@code gcm.googleapis.com}, indicating that the
+message is sent from CCS.</td>
+ </tr>
+ <tr>
+ <td><code>message_id</code></td>
+ <td>Required, string</td>
+ <td>This parameter specifies the original message ID that the receipt is intended for,
+prefixed with {@code dr2:} to indicate that the message is a delivery receipt. A 3rd-party app
+server must send an {@code ack} message with this message ID to acknowledge that it
+received this delivery receipt. See <a href="#table9">table 9</a> for the 'ack' message format.</td>
+ </tr>
+ <tr>
+ <td><code>category</code></td>
+ <td>Optional, string</td>
+ <td>This parameter specifies the application package name of the client app that
+receives the message that this delivery receipt is reporting. This is available when
+{@code message_type} is {@code receipt}.</td>
+ </tr>
+ <tr>
+ <td><code>data</code></td>
+ <td>Optional, string</td>
+ <td>This parameter specifies the key-value pairs for the delivery receipt message. This is available
+when the {@code message_type} is {@code receipt}.
+ <ul>
+ <li>{@code message_status}: This parameter specifies the status of the receipt message.
+It is set to {@code MESSAGE_SENT_TO_DEVICE} to indicate the device has confirmed its receipt of
+the original message.</li>
+ <li>{@code original_message_id}: This parameter specifies the ID of the original message
+that the 3rd-party app server sent to the client app.</li>
+ <li>{@code device_registration_id}: This parameter specifies the registration ID of the
+client app to which the original message was sent.</li>
+ </ul>
+</td>
+ </tr>
+ <tr>
+ <td colspan="3"><strong>Control-specific</strong></td>
+ </tr>
+ <tr>
+ <td><code>control_type</code></td>
+ <td>Optional, string</td>
+ <td><p>This parameter specifies the type of control message sent from CCS.</p>
+ <p>Currently, only {@code CONNECTION_DRAINING} is supported. XMPP (CCS) sends this control message
+before it closes a connection to perform load balancing. As the connection drains, no more messages
+are allowed to be sent to the connection, but existing messages in the pipeline will
+continue to be processed.</p></td>
+ </tr>
+</table>
+
+<h2 id="error-codes">Downstream message error response codes (HTTP and XMPP)</h2>
+
+<p>The following table lists the error response codes for downstream messages (HTTP and XMPP).</p>
+
+<p class="table-caption" id="table11">
+ <strong>Table 11.</strong> Downstream message error response codes.</p>
+<table border="1">
+ <tr>
+ <th>Error</th>
+ <th>HTTP Code</th>
+ <th>XMPP Code</th>
+ <th>Recommended Action</th>
+ </tr>
+ <tr>
+ <td>Missing Registration ID</td>
+ <td>200 + error:MissingRegistration</td>
+ <td><code>INVALID_JSON</code></td>
+ <td>Check that the request contains a registration ID (either in the
+{@code registration_id} in a plain text message, or in the {@code registration_ids} in JSON).</td>
+ </tr>
+ <tr>
+ <td>Invalid Registration ID</td>
+ <td>200 + error:InvalidRegistration</td>
+ <td><code>BAD_REGISTRATION</code></td>
+ <td>Check the format of the registration ID you pass to the server. Make sure it
+matches the registration ID the client app receives from registering with GCM. Do not
+truncate or add additional characters.</td>
+ </tr>
+ <tr>
+ <td>Unregistered Device</td>
+ <td>200 + error:NotRegistered</td>
+ <td><code>DEVICE_UNREGISTERED</code></td>
+ <td>An existing registration ID may cease to be valid in a number of scenarios, including:<br>
+ <ul>
+ <li>If the client app unregisters with GCM.</li>
+ <li>If the client app is automatically unregistered, which can happen if the user uninstalls the application.</li>
+ <li>If the registration ID expires (for example, Google might decide to refresh registration IDs).</li>
+ <li>If the client app is updated but the new version is not configured to receive messages.</li>
+</ul>
+ For all these cases, remove this registration ID from the 3rd-party app
+server and stop using it to send messages.</td>
+ </tr>
+ <tr>
+ <td>Invalid Package Name</td>
+ <td>200 + error:InvalidPackageName</td>
+ <td></td>
+ <td>Make sure the message was addressed to a registration ID whose package name
+matches the value passed in the request.</td>
+ </tr>
+ <tr>
+ <td>Authentication Error</td>
+ <td>401</td>
+ <td>&nbsp;</td>
+ <td>The sender account used to send a message couldn't be authenticated. Possible causes are:<br>
+<ul>
+ <li>Authorization header missing or with invalid syntax in HTTP request.</li>
+ <li>Invalid project number sent as key.</li>
+ <li>Key valid but with GCM service disabled.</li>
+ <li>Request originated from a server not whitelisted in the Server Key IPs.</li>
+</ul>
+ Check that the token you're sending inside the Authentication header is
+the correct API key associated with your project. See
+<a href="{@docRoot}google/gcm/http.html">GCM HTTP Connection Server</a> for details.</td>
+ </tr>
+ <tr>
+ <td>Mismatched Sender</td>
+ <td>200 + error:MismatchSenderId</td>
+ <td><code>BAD_REGISTRATION</code></td>
+ <td>A registration ID is tied to a certain group of senders. When a client app registers
+for GCM, it must specify which senders are allowed to send messages. You should use one
+of those sender IDs when sending messages to the client app. If you switch to a different
+sender, the existing registration IDs won't work.</td>
+ </tr>
+ <tr>
+ <td>Invalid JSON</td>
+ <td>400</td>
+ <td><code>INVALID_JSON</code></td>
+ <td>Check that the JSON message is properly formatted and contains valid fields
+(for instance, making sure the right data type is passed in).</td>
+ </tr>
+ <tr>
+ <td>Message Too Big</td>
+ <td>200 + error:MessageTooBig</td>
+ <td><code>INVALID_JSON</code></td>
+ <td>Check that the total size of the payload data included in a message does
+not exceed 4096 bytes. This includes both the the keys and the values.</td>
+ </tr>
+ <tr>
+ <td>Invalid Data Key</td>
+ <td>200 + error:
+<br />
+InvalidDataKey</td>
+ <td><code>INVALID_JSON</code></td>
+ <td>Check that the payload data does not contain a key (such as {@code from} or any value
+prefixed by {@code google}) that is used internally by GCM. Note that some words (such as {@code collapse_key})
+are also used by GCM but are allowed in the payload, in which case the payload value
+will be overridden by the GCM value.</td>
+ </tr>
+ <tr>
+ <td>Invalid Time to Live</td>
+ <td>200 + error:InvalidTtl</td>
+ <td><code>INVALID_JSON</code></td>
+ <td>Check that the value used in {@code time_to_live} is an integer representing a
+duration in seconds between 0 and 2,419,200 (4 weeks).</td>
+ </tr>
+ <tr>
+ <td>Bad ACK message</td>
+ <td>N/A</td>
+ <td><code>BAD_ACK</code></td>
+ <td>Check that the 'ack' message is properly formatted before retrying. See
+<a href="#table9">table 9</a> for details.</td>
+ </tr>
+ <tr>
+ <td>Timeout</td>
+ <td>5xx or 200 + error:Unavailable</td>
+ <td><code>SERVICE_UNAVAILABLE</code></td>
+ <td><p>The server couldn't process the request in time. Retry the same request, but you must:<br>
+<ul>
+ <li>For HTTP: Honor the {@code Retry-After} header if it is included in the response from the
+GCM Connection Server.</li>
+ <li>Implement exponential back-off in your retry mechanism. (e.g. if you waited one second
+before the first retry, wait at least two second before the next one, then 4 seconds and so on).
+If you're sending multiple messages, delay each one independently by an additional random amount
+to avoid issuing a new request for all messages at the same time.</li>
+ <li>For CCS: The initial retry delay should be set to 1 second.</li>
+</ul>
+ <p>Senders that cause problems risk being blacklisted.</p></td>
+ </tr>
+ <tr>
+ <td>Internal Server Error</td>
+ <td>500 or 200 + error:InternalServerError</td>
+ <td><code>INTERNAL_SERVER_
+<br />
+ERROR</code></td>
+ <td>The server encountered an error while trying to process the request. You could retry
+the same request following the requirements listed in "Timeout" (see row above). If the error persists, please
+report the problem in the {@code android-gcm group}.</td>
+ </tr>
+ <tr>
+ <td>Device Message Rate Exceeded</td>
+ <td>200 + error:
+<br />DeviceMessageRate
+<br />
+Exceeded</td>
+ <td><code>DEVICE_MESSAGE_RATE<br />
+_EXCEEDED</code></td>
+ <td>The rate of messages to a particular device is too high. Reduce the
+number of messages sent to this device and do not immediately retry sending to this device.</td>
+ </tr>
+ <tr>
+ <td>Connection Draining</td>
+ <td>N/A</td>
+ <td><code>CONNECTION_DRAINING</code></td>
+ <td>The message couldn't be processed because the connection is draining. This happens because
+periodically, XMPP (CCS) needs to close down a connection to perform load balancing. Retry the message over
+another XMPP connection.</td>
+ </tr>
+</table>
diff --git a/docs/html/google/gcm/server.jd b/docs/html/google/gcm/server.jd
index 20e2b2e..004fd0e 100644
--- a/docs/html/google/gcm/server.jd
+++ b/docs/html/google/gcm/server.jd
@@ -7,9 +7,9 @@ page.title=Implementing GCM Server
<h2>In this document</h2>
<ol class="toc">
- <li><a href="#choose">Choosing a GCM Connection Server</a></li>
<li><a href="#role">Role of the 3rd-party Application Server</a></li>
- <li><a href="#send-msg">Sending Messages</a>
+ <li><a href="#choose">Choosing a GCM Connection Server</a></li>
+ <li><a href="#send-msg">Sending Messages</a>
<ol class="toc">
<li><a href="#target">Target</a></li>
@@ -17,7 +17,18 @@ page.title=Implementing GCM Server
<li><a href="#params">Message parameters</a>
</ol>
</li>
- <li><a href="#receive">Receiving Messages</a> </li>
+ <li><a href="#adv">Messaging Concepts and Best Practices</a>
+
+ <ol class="toc">
+
+ <li><a href="#collapsible">Send-to-Sync vs. Messages with Payload</a></li>
+ <li><a href="#ttl">Setting an Expiration Date for a Message</a></li>
+ <li><a href="#multi-senders">Receiving Messages from Multiple Senders</a>
+ <li><a href="#lifetime">Lifetime of a Message</a>
+ <li><a href="#throttling">Throttling</a>
+ </ol>
+
+</li>
</li>
</ol>
@@ -25,6 +36,7 @@ page.title=Implementing GCM Server
<h2>See Also</h2>
<ol class="toc">
+<li><a href="server-ref.html">Server Reference</a></li>
<li><a href="gs.html">Getting Started</a></li>
<li><a href="client.html">Implementing GCM Client</a></li>
<li><a href="ccs.html">Cloud Connection Server (XMPP)</a></li>
@@ -37,388 +49,392 @@ page.title=Implementing GCM Server
</div>
-<p>The server side of Google Cloud Messaging (GCM) consists of 2 components:</p>
+<p>The server side of Google Cloud Messaging (GCM) consists of two components:</p>
<ul>
<li>Google-provided <strong>GCM Connection Servers</strong>
-take messages from a 3rd-party application server and send them to a GCM-enabled
-Android application (the &quot;client app&quot;) running on a device. For example,
+take messages from a <a href="{@docRoot}google/gcm/server.html#role">3rd-party app server</a>
+and send them to a GCM-enabled
+application (the &quot;client app&quot;) running on a device. For example,
Google provides connection servers for <a href="{@docRoot}google/gcm/http.html">
-HTTP</a> and <a href="{@docRoot}google/gcm/ccs.html">CCS</a> (XMPP).</li>
+HTTP</a> and <a href="{@docRoot}google/gcm/ccs.html">XMPP (CCS)</a> (XMPP).</li>
<li>A <strong>3rd-party application server</strong> that you must implement. This application
-server sends data to a GCM-enabled Android application via the chosen GCM connection server.</li>
+server sends data to a GCM-enabled client app via the chosen GCM connection server.</li>
</ul>
</p>
+<p>A full GCM implementation requires both a client implementation and a server
+implementation. For more
+information about implementing the client side, see <a href="client.html">
+Implementing GCM Client</a>.</p>
+
+
+<h2 id="role">Role of the 3rd-party Application Server</h2>
+
+<p>Before you can write client apps that use the GCM feature, you must
+have an application server that meets the following criteria:</p>
+
+<ul>
+ <li>Able to communicate with your client.</li>
+ <li>Able to fire off properly formatted requests to the GCM server.</li>
+ <li>Able to handle requests and resend them as needed, using
+<a href="http://en.wikipedia.org/wiki/Exponential_backoff">exponential back-off.</a></li>
+ <li>Able to store the API key and client registration IDs. In HTTP, the API key is
+included in the header of POST requests that send messages. In XMPP, the API key is
+used in the SASL PLAIN authentication request as a password to authenticate the connection.</li>
+ <li>Able to generate message IDs to uniquely identify each message it sends. Message IDs
+should be unique per sender ID.</li>
+</ul>
+
<p>Here are the basic steps you follow to implement your 3rd-party app server:</p>
<ul>
<li>Decide which GCM connection server(s) you want to use. Note that if you want to use
- upstream messaging from your client applications, you must use CCS. For a more detailed
+ upstream messaging from your client applications, you must use XMPP (CCS). For a more detailed
discussion of this, see <a href="#choose">
Choosing a GCM Connection Server</a>.</li>
- <li>Decide how you want to implement your app server. For example:
+ <li>Decide how you want to implement your app server. We provide helper libraries and code
+samples to assist you with your 3rd-party app server implementation. For example:
<ul>
<li>If you decide to use the HTTP connection server, you can use the
GCM server helper library and demo app to help in implementing your app server.</li>
<li>If you decide to use the XMPP connection server, you can use
the provided Python or Java <a href="http://www.igniterealtime.org/projects/smack/">
Smack</a> demo apps as a starting point.</li>
- <li>Note that Google AppEngine does not support connections to CCS.</li>
+ <li>Note that Google AppEngine does not support connections to XMPP (CCS).</li>
</ul>
</li>
</ul>
</li>
</ul>
-<p>A full GCM implementation requires both a client implementation and a server
-implementation. For more
-information about implementing the client side, see <a href="client.html">
-Implementing GCM Client</a>.</p>
<h2 id="choose">Choosing a GCM Connection Server</h2>
<p>Currently GCM provides two connection servers: <a href="{@docRoot}google/gcm/http.html">
-HTTP</a> and <a href="{@docRoot}google/gcm/ccs.html">CCS</a> (XMPP). You can use them
-separately or in tandem. CCS messaging differs from GCM HTTP messaging in the following ways:</p>
+HTTP</a> and <a href="{@docRoot}google/gcm/ccs.html">XMPP (CCS)</a>. You can use them
+separately or in tandem. XMPP (CCS) messaging differs from HTTP messaging in the following ways:</p>
<ul>
<li>Upstream/Downstream messages
<ul>
- <li>GCM HTTP: Downstream only: cloud-to-device. </li>
- <li>CCS: Upstream and downstream (device-to-cloud, cloud-to-device). </li>
+ <li>HTTP: Downstream only, cloud-to-device up to 4KB of data. </li>
+ <li>XMPP (CCS): Upstream and downstream (device-to-cloud, cloud-to-device),
+ up to 4 KB of data. </li>
</ul>
</li>
- <li>Asynchronous messaging
+ <li>Messaging (synchronous or asynchronous)
<ul>
- <li>GCM HTTP: 3rd-party app servers send messages as HTTP POST requests and
-wait for a response. This mechanism is synchronous and causes the sender to block
-before sending another message.</li>
- <li>CCS: 3rd-party app servers connect to Google infrastructure using a
-persistent XMPP connection and send/receive messages to/from all their devices
-at full line speed. CCS sends acknowledgment or failure notifications (in the
+ <li>HTTP: Synchronous. 3rd-party app servers send messages as HTTP POST requests and
+wait for a response. This mechanism is synchronous and blocks the sender from sending
+another message until the response is received.</li>
+ <li>XMPP (CCS): Asynchronous. 3rd-party app servers send/receive messages to/from all their
+devices at full line speed over persistent XMPP connections.
+XMPP (CCS) sends acknowledgment or failure notifications (in the
form of special ACK and NACK JSON-encoded XMPP messages) asynchronously.</li>
</ul>
</li>
<li>JSON
<ul>
- <li>GCM HTTP: JSON messages sent as HTTP POST.</li>
- <li>CCS: JSON messages encapsulated in XMPP messages.</li>
+ <li>HTTP: JSON messages sent as HTTP POST.</li>
+ <li>XMPP (CCS): JSON messages encapsulated in XMPP messages.</li>
+ </ul>
+ </li>
+ <li>Plain Text
+ <ul>
+ <li>HTTP: Plain Text messages sent as HTTP POST.</li>
+ <li>XMPP (CCS): Not supported.</li>
+ </ul>
+ </li>
+ <li>Multicast downstream send to multiple registration IDs.
+ <ul>
+ <li>HTTP: Supported in JSON message format.</li>
+ <li>XMPP (CCS): Not supported.</li>
</ul>
</li>
</ul>
-<h2 id="role">Role of the 3rd-party Application Server</h2>
-<p>Before you can write client Android applications that use the GCM feature, you must
-have an application server that meets the following criteria:</p>
+<h2 id="send-msg">Sending Messages</h2>
-<ul>
- <li>Able to communicate with your client.</li>
- <li>Able to fire off properly formatted requests to the GCM server.</li>
- <li>Able to handle requests and resend them as needed, using
-<a href="http://en.wikipedia.org/wiki/Exponential_backoff">exponential back-off.</a></li>
- <li>Able to store the API key and client registration IDs. The
-API key is included in the header of POST requests that send
-messages.</li>
- <li>Able to generate message IDs to uniquely identify each message it sends. Message IDs
-should be unique per sender ID.</li>
-</ul>
+<p>This section gives an overview of sending messages. For details of message syntax,
+see <a href="{@docRoot}google/gcm/server-ref.html">Server Reference</a>.</p>
-<h2 id="send-msg">Sending Messages</h2>
+<h3>Overview</h3>
<p>Here is the general sequence of events that occurs when a 3rd-party application
-server sends a message:</p>
+server sends a message (the details vary depending on the platform):</p>
<ol>
- <li>The application server sends a message to GCM servers.</li>
- <li>Google enqueues and stores the message in case the device is offline.</li>
- <li>When the device is online, Google sends the message to the device.</li>
- <li>On the device, the system broadcasts the message to the specified Android
-application via Intent broadcast with proper permissions, so that only the targeted
-Android application gets the message. This wakes the Android application up.
-The Android application does not need to be running beforehand to receive the message.</li>
- <li>The Android application processes the message. </li>
+ <li>The 3rd-party app server sends a message to GCM servers.</li>
+ <li>The GCM connection server enqueues and stores the message if the device is offline.</li>
+ <li>When the device is online, GCM connection server sends the message to the device.</li>
+ <li>The client app processes the message. </li>
</ol>
-<p>The following sections describe the basic requirements for
-sending messages.</p>
+<h3>Implement send request</h3>
+
+<p>The following sections describe the basic components involved in
+sending a request. See the <a href="{@docRoot}google/gcm/server-ref.html">Server Reference</a>
+for details.</p>
-<h3 id="target">Target</h3>
+<h4 id="target">Target</h4>
<p>Required. When your app server sends a message in GCM, it must specify a target.</p>
-<p>For HTTP you must specify the target as one of:</p>
+<p>For HTTP you must specify the target as one of the following:</p>
<ul>
<li><code>registration_ids</code>: For sending to 1 or more devices (up to 1000).
When you send a message to multiple registration IDs, that is called a multicast message.</li>
<li><code>notification_key</code>: For sending to multiple devices owned by a single user.</li>
</ul>
-<p>For CCS (XMPP):</p>
+<p>For CCS (XMPP) you must specify the target as:</p>
<ul>
-<li>You must specify the target as the &quot;to&quot; field, where the &quot;to&quot;
+<li>{@code to}: This
field may contain a single registration ID or a notification key.
-CCS does not support multicast messaging.</li>
+XMPP (CCS) does not support multicast messaging.</li>
</ul>
-<h3 id="payload">Payload</h3>
-<p>Optional. If you are including a payload in the message, you use the <code>data</code>
-parameter to include the payload. This applies for both HTTP and CCS.</p>
-
-<h3 id="params">Message parameters</h3>
-
-<p>The following table lists the parameters that a 3rd-party app server might
-include in the JSON messages it sends to a connection server. See the "Where Supported"
-column for information about which connection servers support that particular
-parameter.</p>
-
-<p class="table-caption" id="table1">
- <strong>Table 1.</strong> Message Parameters JSON (CCS and HTTP).</p>
-
-<table>
- <tr>
- <th>Parameter</th>
- <th>Description</th>
-<th>Where Supported</th>
-</tr>
- <td><code>to</code></td>
-<td>In CCS, this parameter is used in place of <code>registration_ids</code> to
-specify the recipient of a message. Its value must be a registration ID.
-The value is a string. Required.</td>
-<td>CCS</td>
-</tr>
-<tr>
-<td><code>message_id</code></td>
-<td>In CCS, this parameter uniquely identifies a message in an XMPP connection.
-The value is a string that uniquely identifies the associated message. Required.</td>
-<td>CCS</td>
-</tr>
-<tr>
-<td><code>message_type</code></td>
-<td>In CCS, this parameter indicates a special status message, typically sent by the system.
-However, your app server also uses this parameter to send an 'ack' or 'nack'
-message back to the CCS connection server. For more discussion of this topic, see
-<a href="ccs.html">Cloud Connection Server</a>. The value is a string. Optional.</td>
-<td>CCS</td>
-<tr>
- <td><code>registration_ids</code></td>
- <td>This parameter specifies a string array containing the list of devices
-(registration IDs) receiving the
-message. It must contain at least 1 and at most 1000 registration IDs. To send a
-multicast message, you must use JSON. For sending a single message to a single
-device, you could use a JSON object with just 1 registration id, or plain text
-(see below). A request must include a recipient&mdash;this can be either a
-registration ID, an array of registration IDs, or a {@code notification_key}.
-Required.</td>
-<td>HTTP</td>
-</tr>
- <tr>
- <td><code>notification_key</code></td>
- <td>This parameter specifies a string that maps a single user to multiple
-registration IDs associated
-with that user. This allows a 3rd-party server to send a single message to
-multiple app instances (typically on multiple devices) owned by a single user.
-A 3rd-party server can use {@code notification_key} as the target for a message
-instead of an individual registration ID (or array of registration IDs). The maximum
-number of members allowed for a {@code notification_key} is 20. For more discussion
-of this topic, see <a href="notifications.html">User Notifications</a>. Optional.
-</td>
-<td style="width:100px">HTTP. This feature is supported in CCS, but you use it by
-specifying a notification key in the &quot;to&quot; field.</td>
-</tr>
- <tr>
- <td><code>collapse_key</code></td>
- <td>This parameter specifies an arbitrary string (such as
-&quot;Updates Available&quot;) that is used
-to collapse a group of like messages
-when the device is offline, so that only the last message gets sent to the
-client. This is intended to avoid sending too many messages to the phone when it
-comes back online. Note that since there is no guarantee of the order in which
-messages get sent, the &quot;last&quot; message may not actually be the last
-message sent by the application server. Messages with collapse keys are also called
-<a href="#s2s">send-to-sync messages</a>.
-<br>
-<strong>Note:</strong> GCM allows a maximum of 4 different collapse keys to be
-used by the GCM server
-at any given time. In other words, the GCM server can simultaneously store 4
-different send-to-sync messages per device, each with a different collapse key.
-If you exceed
-this number GCM will only keep 4 collapse keys, with no guarantees about which
-ones they will be. See <a href="adv.html#collapsible">Advanced Topics</a> for more
-discussion of this topic. Optional.</td>
-<td>CCS, HTTP</td>
-</tr>
- <tr>
- <td><code>data</code></td>
- <td>This parameter specifies a JSON object whose fields represents the
-key-value pairs of the message's
-payload data. If present, the payload data will be
-included in the Intent as application data, with the key being the extra's name.
-For instance, <code>"data":{"score":"3x1"}</code> would result in an intent extra
-named <code>score</code> whose value is the string <code>3x1</code>.
-There is no limit on the number of key/value pairs, though there is a limit on
-the total size of the message (4kb). The values could be any JSON object, but we
-recommend using strings, since the values will be converted to strings in the GCM
-server anyway. If you want to include objects or other non-string data types
-(such as integers or booleans), you have to do the conversion to string yourself.
-Also note that the key cannot be a reserved word (<code>from</code> or any word
-starting with <code>google.</code>). Using words defined in this table as field
-names (such as <code>collapse_key</code>) could yield unpredictable outcomes and
-is not recommended. Optional.</td>
-<td>CCS, HTTP</td>
-</tr>
- <tr>
- <td><code>delay_while_idle</code></td>
- <td>This parameter indicates that the message should not be sent immediately
-if the device is idle. The server will wait for the device to become active, and
-then only the last message for each <code>collapse_key</code> value will be
-sent. The default value is <code>false</code>, and must be a JSON boolean. Optional.</td>
-<td>CCS, HTTP</td>
-</tr>
- <tr>
- <td><code>time_to_live</code></td>
- <td>This parameter specifies how long (in seconds) the message should be kept on GCM
-storage if the device is offline. Optional (default time-to-live is 4 weeks, and must be set as
-a JSON number).</td>
-<td>CCS, HTTP</td>
-</tr>
-<tr>
- <td><code>restricted_package_name</code></td>
- <td>This parameter specifies a string containing the package
-name of your application. When set, messages
-are only sent to registration IDs that match the package name. Optional.
- </td>
-<td>HTTP</td>
-</tr>
-<tr>
- <td><code>dry_run</code></td>
- <td>This parameter allows developers to test a request without actually
-sending a message. Optional. The default value is <code>false</code>, and must
-be a JSON boolean.
- </td>
-<td>HTTP</td>
-</tr>
-<tr>
- <td><code>delivery_receipt_requested</code></td>
- <td>This parameter lets you request confirmation of message delivery. When
-this parameter is set to <code>true</code>, CCS sends a
-delivery receipt when a device confirms that it received a message sent by CCS.
-The default value is <code>false</code>, and must be a JSON boolean. Optional.<br />
-This parameter relates to <a href="{@docRoot}google/gcm/ccs.html#receipts"}>
-delivery receipts</a>.
-</td>
- <td>CCS</td>
-</tr>
-<tr>
- <td><code>message_status</code></td>
- <td>This parameter specifies the status of the receipt message.
-The parameter appears inside the
-<code>&quot;data&quot;</code> field of a
-delivery receipt message. Currently the only possible value
-is <code>MESSAGE_SENT_TO_DEVICE</code>, which indicates that a device acknowledges
-receiving a message sent by CCS.<br />
-This parameter relates to <a href="{@docRoot}google/gcm/ccs.html#receipts"}>
-delivery receipts</a>.</td>
- <td>CCS</td>
-</tr>
-<tr>
- <td><code>original_message_id</code></td>
- <td>The value of this parameter is the ID of the original message that the server sent to
-the device. This parameter appears inside the <code>&quot;data&quot;</code> field of a
-delivery receipt message. <br />
-This parameter relates to <a href="{@docRoot}google/gcm/ccs.html#receipts"}>
-delivery receipts</a>.</td>
- <td>CCS</td>
-</tr>
-<tr>
- <td><code>device_registration_id</code></td>
- <td>For the purpose of tracking the delivery receipt, this parameter lists
-the registration ID of the device to which a given message was sent. This parameter
-appears inside the <code>&quot;data&quot;</code> field of a
-delivery receipt message. <br />
-This parameter relates to <a href="{@docRoot}google/gcm/ccs.html#receipts"}>
-delivery receipts</a>.</td>
- <td>CCS</td>
-</tr>
-
-</table>
+<h4 id="options">Options</h4>
+
+<p>There are various options the 3rd-party app server can set when sending a downstream
+message to a client app. See the <a href="{@docRoot}google/gcm/server-ref.html#table1">
+Server Reference</a> for details. Here are a few examples of possible options:</p>
+
+<ul>
+ <li>{@code collapse_key}: whether a message should be "send-to-sync" or a "message with
+payload".</li>
+ <li>{@code time_to_live}: setting an expiration date for a message.</li>
+ <li>{@code dry_run}: Test your server.
<p>If you want to test your request (either JSON or plain text) without delivering
-the message to the devices, you can set an optional HTTP or JSON parameter called
+the message to the devices, you can set an optional HTTP parameter called
<code>dry_run</code> with the value <code>true</code>. The result will be almost
identical to running the request without this parameter, except that the message
will not be delivered to the devices. Consequently, the response will contain fake
IDs for the message and multicast parameters.</p>
+</li>
+</ul>
-<p>If you are using plain text instead of JSON, the message parameters must be set as
-HTTP parameters sent in the body, and their syntax is slightly different, as
-described in the following table:
-
-<p class="table-caption" id="table2">
- <strong>Table 2.</strong> Message Parameters Plain Text (HTTP only).</p>
-<table>
- <tr>
- <th>Parameter</th>
- <th>Description</th>
- </tr>
- <tr>
- <td><code>registration_id</code></td>
- <td>This parameter specifies the registration ID of the single device
-receiving the message.
-Required.</td>
- </tr>
- <tr>
- <td><code>collapse_key</code></td>
- <td>Same as JSON (see previous table). Optional.</td>
- </tr>
- <tr>
- <td><code>data.&lt;key&gt;</code></td>
-
- <td>This parameter specifies payload data, expressed as parameters
-prefixed with <code>data.</code> and
-suffixed as the key. For instance, a parameter of <code>data.score=3x1</code> would
-result in an intent extra named <code>score</code> whose value is the string
-<code>3x1</code>. There is no limit on the number of key/value parameters, though
-there is a limit on the total size of the message. Also note that the key cannot
-be a reserved word (<code>from</code> or any word starting with
-<code>google.</code>). Using words defined in this table as field
-names (such as <code>collapse_key</code>) could yield unpredictable outcomes and
-is not recommended. Optional.</td>
-
- </tr>
- <tr>
- <td><code>delay_while_idle</code></td>
- <td>This parameter specifies whether messages should be delivered when the device
-is asleep. A value of <code>1</code> or <code>true</code> indicates
-<code>true</code>, and anything else indicates <code>false</code>. Optional. The default
-value is <code>false</code>.</td>
- </tr>
- <tr>
- <td><code>time_to_live</code></td>
- <td>Same as JSON (see previous table). Optional.</td>
- </tr>
-<tr>
- <td><code>restricted_package_name</code></td>
- <td>Same as JSON (see previous table). Optional.
- </td>
-</tr>
-<tr>
- <td><code>dry_run</code></td>
- <td>Same as JSON (see previous table). Optional.
- </td>
-</tr>
-</table>
-
-<h2 id="receive">Receiving Messages</h2>
-
-<p>This is the sequence of events that occurs when an Android application
-installed on a mobile device receives a message:</p>
+<h4 id="payload">Payload</h4>
+<p>Optional. If you are including a payload in the message, you use the <code>data</code>
+parameter to include the payload. This applies for both HTTP and XMPP.</p>
+
+<p>See the <a href="{@docRoot}google/gcm/server-ref.html">Server Reference</a> for details on sending
+and receiving messages.</p>
+
+<h2 id="adv">Messaging Concepts and Best Practices</h2>
+
+<p>This section has a discussion of general messaging topics.</p>
+
+<h3 id="collapsible">Send-to-Sync vs. Messages with Payload</h3>
+
+<p>Every message sent in GCM has the following characteristics:</p>
+<ul>
+ <li>It has a payload limit of 4096 bytes.</li>
+ <li>By default, it is stored by GCM for 4 weeks.</li>
+</ul>
+
+<p>But despite these similarities, messages can behave very differently depending
+on their particular settings. One major distinction between messages is whether
+they are collapsed (where each new message replaces the preceding message) or not
+collapsed (where each individual message is delivered). Every message sent in GCM
+is either a &quot;send-to-sync&quot; (collapsible) message or a &quot;message with
+payload&quot; (non-collapsible message).</p>
+
+<h4 id="s2s">Send-to-sync messages</h4>
+
+<p>A send-to-sync (collapsible) message is often a &quot;tickle&quot; that tells
+a mobile application to sync data from the server. For example, suppose you have
+an email application. When a user receives new email on the server, the server
+pings the mobile application with a &quot;New mail&quot; message. This tells the
+application to sync to the server to pick up the new email. The server might send
+this message multiple times as new mail continues to accumulate, before the application
+has had a chance to sync. But if the user has received 25 new emails, there's no
+need to preserve every &quot;New mail&quot; message. One is sufficient. Another
+example would be a sports application that updates users with the latest score.
+Only the most recent message is relevant. </p>
+
+<p>GCM allows a maximum of 4 different collapse keys to be used by the GCM server
+at any given time. In other words, the GCM server can simultaneously store 4
+different send-to-sync messages per device, each with a different collapse key.
+For example, Device A can have A1, A2, A3, and A4. Device B can have B1, B2, B3,
+and B4, and so on. If you exceed this number GCM will only keep 4 collapse keys, with no
+guarantees about which ones they will be.</p>
+
+<h3 id="payload">Messages with payload</h3>
+
+<p>Unlike a send-to-sync message, every &quot;message with payload&quot;
+(non-collapsible message) is delivered. The payload the message contains can be
+up to 4kb. For example, here is a JSON-formatted message in an IM application in
+which spectators are discussing a sporting event:</p>
+
+<pre class="prettyprint pretty-json">{
+ "registration_id" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
+ "data" : {
+ "Nick" : "Mario",
+ "Text" : "great match!",
+ "Room" : "PortugalVSDenmark",
+ },
+}</pre>
+
+<p>A &quot;message with payload&quot; is not simply a &quot;ping&quot; to the
+mobile application to contact the server to fetch data. In the aforementioned IM
+application, for example, you would want to deliver every message, because every
+message has different content. To specify a non-collapsible message, you simply
+omit the <code>collapse_key</code> parameter. Thus GCM will send each message
+individually. Note that the order of delivery is not guaranteed.</p>
+
+<p>GCM will store up to 100 non-collapsible messages. After that, all messages
+are discarded from GCM, and a new message is created that tells the client how
+far behind it is.</p>
+
+<p>The application should respond by syncing with the server to recover the
+discarded messages. </p>
+
+<h4 id="which">Which should I use?</h4>
+ <p>If your application does not need to use non-collapsible messages, collapsible
+messages are a better choice from a performance standpoint. However, if you use
+collapsible messages, remember that <strong>GCM only allows a maximum of 4 different collapse
+keys to be used by the GCM server per registration ID at any given time</strong>. You must
+not exceed this number, or it could cause unpredictable consequences.</p>
+
+<h3 id="ttl">Setting an Expiration Date for a Message</h3>
+<p>You can use the <code>time_to_live</code> parameter in the send request
+to specify the maximum lifespan of a message.
+The value of this parameter must be a duration from 0 to 2,419,200 seconds, and
+it corresponds to the maximum period of time for which GCM will store and try to
+deliver the message. Requests that don't contain this field default to the maximum
+period of 4 weeks.</p>
+<p>Here are some possible uses for this feature:</p>
+<ul>
+ <li>Video chat incoming calls</li>
+ <li>Expiring invitation events</li>
+ <li>Calendar events</li>
+</ul>
+<h4 id="bg">Background </h4>
+<p>GCM usually delivers messages immediately after they are sent. However,
+this might not always be possible. For example, if the platform is Android,
+the device could be turned off, offline, or otherwise unavailable.
+Or the sender itself might request
+that messages not be delivered until the device becomes active by using the
+<code>delay_while_idle</code> flag. Finally, GCM might intentionally delay messages
+to prevent an application from consuming excessive resources and negatively
+impacting battery life.</p>
+
+<p>When this happens, GCM will store the message and deliver it as soon as it's
+feasible. While this is fine in most cases, there are some applications for which
+a late message might as well never be delivered. For example, if the message is
+an incoming call or video chat notification, it will only be meaningful for a
+small period of time before the call is terminated. Or if the message is an
+invitation to an event, it will be useless if received after the event has ended.</p>
+
+<p>Another advantage of specifying the expiration date for a message is that GCM
+will never throttle messages with a <code>time_to_live</code> value of 0 seconds.
+In other words, GCM will guarantee best effort for messages that must be delivered
+&quot;now or never.&quot; Keep in mind that a <code>time_to_live</code> value of
+0 means messages that can't be delivered immediately will be discarded. However,
+because such messages are never stored, this provides the best latency for
+sending notifications.</p>
+
+<p>Here is an example of a JSON-formatted request that includes TTL:</p>
+<pre class="prettyprint pretty-json">
+{
+ "collapse_key" : "demo",
+ "delay_while_idle" : true,
+ "registration_ids" : ["xyz"],
+ "data" : {
+ "key1" : "value1",
+ "key2" : "value2",
+ },
+ "time_to_live" : 3
+},
+</pre>
+
+
+<h3 id="multi-senders">Receiving Messages from Multiple Senders</h3>
+
+<p>GCM allows multiple parties to send messages to the same application. For
+example, suppose your application is an articles aggregator with multiple
+contributors, and you want each of them to be able to send a message when they
+publish a new article. This message might contain a URL so that the application
+can download the article. Instead of having to centralize all sending activity in
+one location, GCM gives you the ability to let each of these contributors send
+its own messages.</p>
+
+<p>To make this possible, all you need to do is have each sender generate its own
+project number. Then include those IDs in the sender field, separated by commas,
+when requesting a registration. Finally, share the registration ID with your
+partners, and they'll be able to send messages to your application using their
+own authentication keys.</p>
+
+<p>Note that there is limit of 100 multiple senders.</p>
+
+<h3 id="lifetime">Lifetime of a Message</h3>
+
+<p>When a 3rd-party server posts a message to GCM and receives a message ID back,
+it does not mean that the message was already delivered to the device. Rather, it
+means that it was accepted for delivery. What happens to the message after it is
+accepted depends on many factors.</p>
+
+<p>In the best-case scenario, if the device is connected to GCM, the screen is on,
+and there are no throttling restrictions (see <a href="#throttling">Throttling</a>),
+the message will be delivered right away.</p>
+
+<p>If the device is connected but idle, the message will still be
+delivered right away unless the <code>delay_while_idle</code> flag is set to true.
+Otherwise, it will be stored in the GCM servers until the device is awake. And
+that's where the <code>collapse_key</code> flag plays a role: if there is already
+a message with the same collapse key (and registration ID) stored and waiting for
+delivery, the old message will be discarded and the new message will take its place
+(that is, the old message will be collapsed by the new one). However, if the collapse
+key is not set, both the new and old messages are stored for future delivery.
+Collapsible messages are also called <a href="#s2s">send-to-sync messages</a>.</p>
+
+<p class="note"><strong>Note:</strong> There is a limit on how many messages can
+be stored without collapsing. That limit is currently 100. If the limit is reached,
+all stored messages are discarded. Then when the device is back online, it receives
+a special message indicating that the limit was reached. The application can then
+handle the situation properly, typically by requesting a full sync.
+<br><br>
+Likewise, there is a limit on how many <code>collapse_key</code>s you can have for
+a particular device. GCM allows a maximum of 4 different collapse keys to be used
+by the GCM server per device
+any given time. In other words, the GCM server can simultaneously store 4 different
+send-to-sync messages, each with a different collapse key. If you exceed this number
+GCM will only keep 4 collapse keys, with no guarantees about which ones they will be.
+See <a href="#s2s">Send-to-sync messages</a> for more information.
+</p>
+
+<p>If the device is not connected to GCM, the message will be stored until a
+connection is established (again respecting the collapse key rules). When a connection
+is established, GCM will deliver all pending messages to the device, regardless of
+the <code>delay_while_idle</code> flag. If the device never gets connected again
+(for instance, if it was factory reset), the message will eventually time out and
+be discarded from GCM storage. The default timeout is 4 weeks, unless the
+<code>time_to_live</code> flag is set.</p>
+
+<p>Finally, when GCM attempts to deliver a message to the device and the
+application was uninstalled, GCM will discard that message right away and
+invalidate the registration ID. Future attempts to send a message to that device
+will get a <code>NotRegistered</code> error. See <a href="#unreg">
+How Unregistration Works</a> for more information.</p>
+<p>Although is not possible to track the status of each individual message, the
+Google Cloud Console stats are broken down by messages sent to device, messages
+collapsed, and messages waiting for delivery.</p>
+
+<h3 id="throttling">Throttling</h3>
+<p>To prevent abuse (such as sending a flood of messages to a device) and
+to optimize for the overall network efficiency and battery life of
+devices, GCM implements throttling of messages using a token bucket
+scheme. Messages are throttled on a per application and per <a href="#collapsible">collapse
+key</a> basis (including non-collapsible messages). Each application
+collapse key is granted some initial tokens, and new tokens are granted
+periodically therefter. Each token is valid for a single message sent to
+the device. If an application collapse key exhausts its supply of
+available tokens, new messages are buffered in a pending queue until
+new tokens become available at the time of the periodic grant. Thus
+throttling in between periodic grant intervals may add to the latency
+of message delivery for an application collapse key that sends a large
+number of messages within a short period of time. Messages in the pending
+queue of an application collapse key may be delivered before the time
+of the next periodic grant, if they are piggybacked with messages
+belonging to a non-throttled category by GCM for network and battery
+efficiency reasons.</p>
-<ol>
- <li>The system receives the incoming message and extracts the raw key/value
-pairs from the message payload, if any.</li>
- <li>The system passes the key/value pairs to the targeted Android application
-in a <code>com.google.android.c2dm.intent.RECEIVE</code> Intent as a set of
-extras.</li>
- <li>The Android application extracts the raw data
-from the <code>com.google.android.c2dm.intent.RECEIVE</code><code> </code>Intent
-by key and processes the data.</li>
-</ol>
-<p>See the documentation for each connection server for more detail on how it
-handles responses.</p>
diff --git a/docs/html/google/google_toc.cs b/docs/html/google/google_toc.cs
index 0c48a0a..4e8e638 100644
--- a/docs/html/google/google_toc.cs
+++ b/docs/html/google/google_toc.cs
@@ -169,22 +169,15 @@
<span class="en">HTTP</span></a></li>
</ul>
</li>
+ <li><a href="<?cs var:toroot?>google/gcm/server-ref.html">
+ <span class="en">Server Reference</span></a>
+ </li>
<li><a href="<?cs var:toroot?>google/gcm/notifications.html">
<span class="en">User Notifications</span></a>
</li>
- <li><a href="<?cs var:toroot?>google/gcm/adv.html">
- <span class="en">Advanced Topics</span></a>
- </li>
<li><a href="<?cs var:toroot?>google/gcm/c2dm.html">
<span class="en">Migration</span></a>
</li>
- <li id="gcm-tree-list" class="nav-section">
- <div class="nav-section-header">
- <a href="<?cs var:toroot ?>reference/gcm-packages.html">
- <span class="en">Reference</span>
- </a>
- <div>
- </li>
</ul>
</li>
diff --git a/docs/html/google/play-services/ads.jd b/docs/html/google/play-services/ads.jd
index e4f0b2c..2f915f3 100644
--- a/docs/html/google/play-services/ads.jd
+++ b/docs/html/google/play-services/ads.jd
@@ -98,10 +98,8 @@ header.hide=1
serve banner and interstitial ads using the Google Mobile Ads APIs.</p>
<h4>3. Read the documentation</h4>
- <p>Read the <a class="external-link" href="https://www.google.com/adsense/localized-terms">AdSense
- Terms of Service</a> and the <a class="external-link"
- href="https://support.google.com/admob/topic/1307235?hl=en&ref_topic=1307209">AdMob
- publisher guidelines and policies</a>.</p>
+ <p>Your use of the Google Mobile Ads SDK is governed by the terms between you and Google that
+ govern your use of the Google product (AdSense/AdMob, AdX or DFP) with which you use the SDK.</p>
<p>For quick access while developing your Android apps, the <a
href="{@docRoot}reference/gms-packages.html">Google Mobile Ads API reference</a> is available here on
developer.android.com.</p>
diff --git a/docs/html/google/play/billing/billing_integrate.jd b/docs/html/google/play/billing/billing_integrate.jd
index 052cf75..e3cacf9 100644
--- a/docs/html/google/play/billing/billing_integrate.jd
+++ b/docs/html/google/play/billing/billing_integrate.jd
@@ -232,7 +232,7 @@ startIntentSenderForResult(pendingIntent.getIntentSender(),
1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
Integer.valueOf(0));
</pre>
-<p>Google Plays sends a response to your {@link android.app.PendingIntent} to the {@link android.app.Activity#onActivityResult onActivityResult} method of your application. The {@link android.app.Activity#onActivityResult onActivityResult} method will have a result code of {@code Activity.RESULT_OK} (1) or {@code Activity.RESULT_CANCELED} (0). To see the types of order information that is returned in the response {@link android.content.Intent}, see <a href="{@docRoot}google/play/billing/billing_reference.html#getBuyIntent">In-app Billing Reference</a>.</p>
+<p>Google Play sends a response to your {@link android.app.PendingIntent} to the {@link android.app.Activity#onActivityResult onActivityResult} method of your application. The {@link android.app.Activity#onActivityResult onActivityResult} method will have a result code of {@code Activity.RESULT_OK} (1) or {@code Activity.RESULT_CANCELED} (0). To see the types of order information that is returned in the response {@link android.content.Intent}, see <a href="{@docRoot}google/play/billing/billing_reference.html#getBuyIntent">In-app Billing Reference</a>.</p>
<p>The purchase data for the order is a String in JSON format that is mapped to the {@code INAPP_PURCHASE_DATA} key in the response {@link android.content.Intent}, for example:
<pre>
@@ -243,11 +243,19 @@ startIntentSenderForResult(pendingIntent.getIntentSender(),
"purchaseTime":1345678900000,
"purchaseState":0,
"developerPayload":"bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
- "purchaseToken":"rojeslcdyyiapnqcynkjyyjh"
+ "purchaseToken":<em>"opaque-token-up-to-1000-characters"</em>
}'
</pre>
</p>
+<p class="note"><strong>Note:</strong> Google Play generates a token for the
+purchase. This token is an opaque character sequence that may be up to 1,000
+characters long. Pass this entire token to other methods, such as when you
+consume the purchase, as described in
+<a href="{@docRoot}training/in-app-billing/purchase-iab-products.html#Consume">Consume
+a Purchase</a>. Do not abbreviate or truncate this token; you must save and
+return the entire token.</p>
+
<p>Continuing from the previous example, you get the response code, purchase data, and signature from the response {@link android.content.Intent}.</p>
<pre>
&#64;Override
diff --git a/docs/html/google/play/billing/billing_reference.jd b/docs/html/google/play/billing/billing_reference.jd
index 902c2c6..da9178d 100644
--- a/docs/html/google/play/billing/billing_reference.jd
+++ b/docs/html/google/play/billing/billing_reference.jd
@@ -202,7 +202,12 @@ RSASSA-PKCS1-v1_5 scheme.</td>
</tr>
<tr>
<td>{@code purchaseToken}</td>
- <td>A token that uniquely identifies a purchase for a given item and user pair. </td>
+ <td>A token that uniquely identifies a purchase for a given item and user
+ pair. This token may be up to 1,000 characters long.
+ Pass this entire token to other methods, such as when you consume the
+ purchase (as described in
+<a href="{@docRoot}training/in-app-billing/purchase-iab-products.html#Consume">Consume
+ a Purchase</a>). Do not abbreviate or truncate this token.</td>
</tr>
</table>
</p>
diff --git a/docs/html/guide/practices/screens_support.jd b/docs/html/guide/practices/screens_support.jd
index 7ebda53..7c963dd 100644
--- a/docs/html/guide/practices/screens_support.jd
+++ b/docs/html/guide/practices/screens_support.jd
@@ -1,5 +1,5 @@
page.title=Supporting Multiple Screens
-page.metaDescription=Nanaging UIs for the best display on multiple screen sizes.
+page.metaDescription=Managing UIs for the best display on multiple screen sizes.
meta.tags="multiple screens"
@jd:body
@@ -348,13 +348,13 @@ can use for density-specific resources are <code>ldpi</code> (low), <code>mdpi</
<code>hdpi</code> (high), <code>xhdpi</code> extra-high), <code>xxhdpi</code>
(extra-extra-high), and <code>xxxhdpi</code> (extra-extra-extra-high). For example, bitmaps
for high-density screens should go in {@code drawable-hdpi/}.</p>
- <p class="note" id="xxxhdpi-note"><strong>Note:</strong> the <code>drawable-xxxhdpi</code>
+ <p class="note" id="xxxhdpi-note"><strong>Note:</strong> The <code>mipmap-xxxhdpi</code>
qualifier is necessary only to provide a launcher icon that can appear larger than usual on an
xxhdpi device. You do not need to provide xxxhdpi assets for all your app's images.</p>
<p>Some devices scale-up the launcher icon by as much as 25%. For example, if your highest
density launcher icon image is already extra-extra-high-density, the scaling process will make it
appear less crisp. So you should provide a higher density launcher icon in the
-<code>drawable-xxxhdpi</code> directory, which the system uses instead of scaling up a smaller
+<code>mipmap-xxxhdpi</code> directory, which the system uses instead of scaling up a smaller
version of the icon.</p>
<p>See <a href="{@docRoot}design/style/iconography.html#xxxhdpi-launcher">Provide an
xxx-high-density launcher icon</a> for more information. You should not use the
@@ -362,6 +362,16 @@ xxx-high-density launcher icon</a> for more information. You should not use the
</li>
</ul>
+<p class="note"><strong>Note:</strong> Place all your launcher icons in the
+<code>res/mipmap-[density]/</code> folders, rather than the <code>res/drawable-[density]/</code>
+folders. The Android system retains the resources in these density-specific folders, such as
+mipmap-xxxhdpi, regardless of the screen resolution of the device where your app is installed. This
+behavior allows launcher apps to pick the best resolution icon for your app to display on the home
+screen. For more information about using the mipmap folders, see
+<a href="{@docRoot}tools/project/index.html#mipmap">Managing Projects Overview</a>.
+</p>
+
+
<p>The size and density configuration qualifiers correspond to the generalized sizes and densities
described in <a href="#range">Range of screens supported</a>, above.</p>
@@ -538,9 +548,9 @@ screen sizes (instead of using the size qualifiers in table 1).</p></p>
sizes and densities, see <a href="#range">Range of Screens Supported</a>, earlier in this
document.</p>
-<p>For example, the following is a list of resource directories in an application that
-provides different layout designs for different screen sizes and different bitmap drawables
-for medium, high, and extra-high-density screens.</p>
+<p>For example, the following application resource directories provide different layout designs
+for different screen sizes and different drawables. Use the <code>mipmap/</code> folders for
+launcher icons.</p>
<pre class="classic">
res/layout/my_layout.xml // layout for normal screen size ("default")
@@ -548,10 +558,16 @@ res/layout-large/my_layout.xml // layout for large screen size
res/layout-xlarge/my_layout.xml // layout for extra-large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra-large in landscape orientation
-res/drawable-mdpi/my_icon.png // bitmap for medium-density
-res/drawable-hdpi/my_icon.png // bitmap for high-density
-res/drawable-xhdpi/my_icon.png // bitmap for extra-high-density
-res/drawable-xxhdpi/my_icon.png // bitmap for extra-extra-high-density
+res/drawable-mdpi/graphic.png // bitmap for medium-density
+res/drawable-hdpi/graphic.png // bitmap for high-density
+res/drawable-xhdpi/graphic.png // bitmap for extra-high-density
+res/drawable-xxhdpi/graphic.png // bitmap for extra-extra-high-density
+
+res/mipmap-mdpi/my_icon.png // launcher icon for medium-density
+res/mipmap-hdpi/my_icon.png // launcher icon for high-density
+res/mipmap-xhdpi/my_icon.png // launcher icon for extra-high-density
+res/mipmap-xxhdpi/my_icon.png // launcher icon for extra-extra-high-density
+res/mipmap-xxxhdpi/my_icon.png // launcher icon for extra-extra-extra-high-density
</pre>
<p>For more information about how to use alternative resources and a complete list of
@@ -560,7 +576,7 @@ configuration qualifiers (not just for screen configurations), see
Providing Alternative Resources</a>.</p>
<p>Be aware that, when the Android system picks which resources to use at runtime, it uses
-certain logic to determing the "best matching" resources. That is, the qualifiers you use don't
+certain logic to determine the "best matching" resources. That is, the qualifiers you use don't
have to exactly match the current screen configuration in all cases in order for the system to
use them. Specifically, when selecting resources based on the size qualifiers, the system will
use resources designed for a screen smaller than the current screen if there are no resources
@@ -703,10 +719,10 @@ such, you can now specify that these layout resources should be used only when t
smallest width your layout supports once it's complete.</p>
<p class="note"><strong>Note:</strong> Remember that all the figures used with these new size APIs
-are density-indpendent pixel (dp) values and your layout dimensions should also always be defined
+are density-independent pixel (dp) values and your layout dimensions should also always be defined
using dp units, because what you care about is the amount of screen space available after the system
accounts for screen density (as opposed to using raw pixel resolution). For more information about
-density-indpendent pixels, read <a href="#terms">Terms and concepts</a>, earlier in this
+density-independent pixels, read <a href="#terms">Terms and concepts</a>, earlier in this
document.</p>
@@ -728,7 +744,7 @@ Also beware that the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action B
a part of your application's window space, although your layout does not declare it, so it reduces
the space available for your layout and you must account for it in your design.</p>
-<p class="table-caption"><strong>Table 2.</strong> New configuration qualifers for screen size
+<p class="table-caption"><strong>Table 2.</strong> New configuration qualifiers for screen size
(introduced in Android 3.2).</p>
<table>
<tr><th>Screen configuration</th><th>Qualifier values</th><th>Description</th></tr>
@@ -745,7 +761,7 @@ height and width (you may also think of it as the "smallest possible width" for
use this qualifier to ensure that, regardless of the screen's current orientation, your
application's has at least {@code &lt;N&gt;} dps of width available for its UI.</p>
<p>For example, if your layout requires that its smallest dimension of screen area be at
-least 600 dp at all times, then you can use this qualifer to create the layout resources, {@code
+least 600 dp at all times, then you can use this qualifier to create the layout resources, {@code
res/layout-sw600dp/}. The system will use these resources only when the smallest dimension of
available screen is at least 600dp, regardless of whether the 600dp side is the user-perceived
height or width. The smallestWidth is a fixed screen size characteristic of the device; <strong>the
@@ -851,7 +867,7 @@ res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger
res/layout-sw720dp/main_activity.xml # For 10” tablets (720dp wide and bigger)
</pre>
-<p>Notice that the previous two sets of example resources use the "smallest width" qualifer, {@code
+<p>Notice that the previous two sets of example resources use the "smallest width" qualifier, {@code
sw&lt;N&gt;dp}, which specifies the smallest of the screen's two sides, regardless of the
device's current orientation. Thus, using {@code sw&lt;N&gt;dp} is a simple way to specify the
overall screen size available for your layout by ignoring the screen's orientation.</p>
@@ -1392,4 +1408,4 @@ between 0.1 and 3 that represents the desired scaling factor.</p>
<p>For more information about creating AVDs from the command line, see <a
href="{@docRoot}tools/devices/managing-avds-cmdline.html">Managing AVDs from the
-Command Line</a>.</p> \ No newline at end of file
+Command Line</a>.</p>
diff --git a/docs/html/guide/topics/data/backup.jd b/docs/html/guide/topics/data/backup.jd
index f09ff9e..5710a47 100644
--- a/docs/html/guide/topics/data/backup.jd
+++ b/docs/html/guide/topics/data/backup.jd
@@ -643,7 +643,8 @@ public class MyPrefsBackupAgent extends BackupAgentHelper {
// Allocate a helper and add it to the backup agent
&#64;Override
public void onCreate() {
- SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
+ SharedPreferencesBackupHelper helper =
+ new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
@@ -688,8 +689,10 @@ public class MyFileBackupAgent extends BackupAgentHelper {
static final String FILES_BACKUP_KEY = "myfiles";
// Allocate a helper and add it to the backup agent
- void onCreate() {
- FileBackupHelper helper = new FileBackupHelper(this, TOP_SCORES, PLAYER_STATS);
+ &#64;Override
+ public void onCreate() {
+ FileBackupHelper helper = new FileBackupHelper(this,
+ TOP_SCORES, PLAYER_STATS);
addHelper(FILES_BACKUP_KEY, helper);
}
}
diff --git a/docs/html/guide/topics/media/exoplayer.jd b/docs/html/guide/topics/media/exoplayer.jd
index 17b4669..1e8601f 100644
--- a/docs/html/guide/topics/media/exoplayer.jd
+++ b/docs/html/guide/topics/media/exoplayer.jd
@@ -72,10 +72,8 @@ page.tags="audio","video","adaptive","streaming","DASH","smoothstreaming"
<ul>
<li><a class="external-link" href="https://github.com/google/ExoPlayer/tree/master/library">
ExoPlayer Library</a> &mdash; This part of the project contains the core library classes.</li>
- <li><a class="external-link" href="https://github.com/google/ExoPlayer/tree/master/demo/src/main/java/com/google/android/exoplayer/demo/simple">
- Simple Demo</a> &mdash; This part of the app demonstrates a basic use of ExoPlayer.</li>
- <li><a class="external-link" href="https://github.com/google/ExoPlayer/tree/master/demo/src/main/java/com/google/android/exoplayer/demo/full">
- Full Demo</a> &mdash; This part of the app demonstrates more advanced features,
+ <li><a class="external-link" href="https://github.com/google/ExoPlayer/tree/master/demo">
+ Demo App</a> &mdash; This part of the project demonstrates usage of ExoPlayer,
including the ability to select between multiple audio tracks, a background audio mode,
event logging and DRM protected playback. </li>
</ul>
@@ -137,9 +135,10 @@ player.setPlayWhenReady(true);
player.release(); // Don’t forget to release when done!
</pre>
-<p>For a complete example, see the {@code SimplePlayerActivity} in the ExoPlayer demo app, which
- correctly manages an ExoPlayer instance with respect to both the {@link android.app.Activity} and
- {@link android.view.Surface} lifecycles.</p>
+<p>For a complete example, see {@code PlayerActivity} and {@code DemoPlayer} in the ExoPlayer demo
+ app. Between them these classes correctly manage an ExoPlayer instance with respect to both the
+ {@link android.app.Activity} and {@link android.view.Surface} lifecycles.
+</p>
<h2 id="samplesource">SampleSource</h2>
@@ -187,7 +186,7 @@ MediaCodecAudioTrackRenderer audioRenderer = new MediaCodecAudioTrackRenderer(
</pre>
<p>The ExoPlayer demo app provides a complete implementation of this code in
- {@code DefaultRendererBuilder}. The {@code SimplePlaybackActivity} class uses it to play one
+ {@code DefaultRendererBuilder}. The {@code PlayerActivity} class uses it to play one
of the videos available in the demo app. Note that in the example, video and audio
are muxed, meaning they are streamed together from a single URI. The {@code FrameworkSampleSource}
instance provides video samples to the {@code videoRenderer} object and audio samples to the
@@ -211,9 +210,9 @@ MediaCodecAudioTrackRenderer audioRenderer = new MediaCodecAudioTrackRenderer(
which loads chunks of media data from which individual samples can be extracted. Each {@code
ChunkSampleSource} requires a {@code ChunkSource} object to be injected through its constructor,
which is responsible for providing media chunks from which to load and read samples. The {@code
- DashMp4ChunkSource} and {@code SmoothStreamingChunkSource} classes provide DASH and SmoothStreaming
- playback using the FMP4 container format. The {@code DashWebMChunkSource} class uses the WebM
- container format to provide DASH playback.</p>
+ DashChunkSource} class provides DASH playback using the FMP4 and WebM container formats. The
+ {@code SmoothStreamingChunkSource} class provides SmoothStreaming playback using the FMP4
+ container format.</p>
<p>All of the standard {@code ChunkSource} implementations require a {@code FormatEvaluator} and
a {@code DataSource} to be injected through their constructors. The {@code FormatEvaluator}
@@ -242,7 +241,7 @@ BandwidthMeter bandwidthMeter = new BandwidthMeter();
// Build the video renderer.
DataSource videoDataSource = new HttpDataSource(userAgent,
HttpDataSource.REJECT_PAYWALL_TYPES, bandwidthMeter);
-ChunkSource videoChunkSource = new DashMp4ChunkSource(videoDataSource,
+ChunkSource videoChunkSource = new DashChunkSource(videoDataSource,
new AdaptiveEvaluator(bandwidthMeter), videoRepresentations);
ChunkSampleSource videoSampleSource = new ChunkSampleSource(videoChunkSource,
loadControl, VIDEO_BUFFER_SEGMENTS * BUFFER_SEGMENT_SIZE, true);
@@ -253,7 +252,7 @@ MediaCodecVideoTrackRenderer videoRenderer = new MediaCodecVideoTrackRenderer(
// Build the audio renderer.
DataSource audioDataSource = new HttpDataSource(userAgent,
HttpDataSource.REJECT_PAYWALL_TYPES, bandwidthMeter);
-ChunkSource audioChunkSource = new DashMp4ChunkSource(audioDataSource,
+ChunkSource audioChunkSource = new DashChunkSource(audioDataSource,
new FormatEvaluator.FixedEvaluator(), audioRepresentation);
SampleSource audioSampleSource = new ChunkSampleSource(audioChunkSource,
loadControl, AUDIO_BUFFER_SEGMENTS * BUFFER_SEGMENT_SIZE, true);
@@ -273,9 +272,8 @@ MediaCodecAudioTrackRenderer audioRenderer = new MediaCodecAudioTrackRenderer(
</p>
<p>The ExoPlayer demo app provides complete implementation of this code in
- {@code DashVodRendererBuilder}. The {@code SimplePlaybackActivity} class uses this builder to
- construct renderers for playing DASH sample videos in the demo app. It asynchronously fetches a
- specified MPD file in order to construct the required {@code Representation} objects. For an
+ {@code DashRendererBuilder}. The {@code PlayerActivity} class uses this builder to
+ construct renderers for playing DASH sample videos in the demo app. For an
equivalent SmoothStreaming example, see the {@code SmoothStreamingRendererBuilder} class in the
demo app.</p>
@@ -313,7 +311,7 @@ if (format.width * format.height &lt;= maxDecodableFrameSize) {
}
</pre>
-<p>This approach is used to filter {@code Representations} in the {@code DashVodRendererBuilder}
+<p>This approach is used to filter {@code Representations} in the {@code DashRendererBuilder}
class of the ExoPlayer demo app, and similarly to filter track indices in {@code
SmoothStreamingRendererBuilder}.</p>
@@ -372,24 +370,26 @@ boolean isAdaptive = MediaCodecUtil.getDecoderInfo(MimeTypes.VIDEO_H264).adaptiv
<p>In addition to high level listeners, many of the individual components provided by the
ExoPlayer library allow their own event listeners. For example, {@code
MediaCodecVideoTrackRenderer} has constructors that take a {@code
- MediaCodecVideoTrackRenderer.EventListener}. In the ExoPlayer demo app, {@code SimplePlayerActivity}
- acts as a listener so that it can adjust the dimensions of the target surface to have the correct
- height and width ratio for the video being played:</p>
+ MediaCodecVideoTrackRenderer.EventListener}. In the ExoPlayer demo app, {@code DemoPlayer}
+ acts as the listener to multiple individual components, forwarding events to {@code PlayerActivity}.
+ This approach allows {@code PlayerActivity} to adjust the dimensions of the target surface
+ to have the correct height and width ratio for the video being played:</p>
<pre>
&#64;Override
-public void onVideoSizeChanged(int width, int height) {
- surfaceView.setVideoWidthHeightRatio(height == 0 ? 1 : (float) width / height);
+public void onVideoSizeChanged(int width, int height, float pixelWidthAspectRatio) {
+ surfaceView.setVideoWidthHeightRatio(
+ height == 0 ? 1 : (width * pixelWidthAspectRatio) / height);
}
</pre>
-<p>The {@code RendererBuilder} classes in the ExoPlayer demo app inject the activity as the
- listener, for example in the {@code DashVodRendererBuilder} class:</p>
+<p>The {@code RendererBuilder} classes in the ExoPlayer demo app inject the {@code DemoPlayer} as
+ the listener to each component, for example in the {@code DashRendererBuilder} class:</p>
<pre>
MediaCodecVideoTrackRenderer videoRenderer = new MediaCodecVideoTrackRenderer(
- videoSampleSource, null, true, MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT,
- 0, <strong>mainHandler, playerActivity</strong>, 50);
+ sampleSource, null, true, MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT, 5000,
+ null, <strong>player.getMainHandler(), player</strong>, 50);
</pre>
<p>Note that you must pass a {@link android.os.Handler} object to the renderer, which determines
@@ -441,9 +441,7 @@ player.blockingSendMessage(videoRenderer,
<p>You must use a blocking message because the contract of {@link
android.view.SurfaceHolder.Callback#surfaceDestroyed surfaceDestroyed()} requires that the
- app does not attempt to access the surface after the method returns. The {@code
- SimplePlayerActivity} class in the demo app demonstrates how the surface should be set and
- cleared.</p>
+ app does not attempt to access the surface after the method returns.</p>
<h2 id="customizing">Customizing ExoPlayer</h2>
diff --git a/docs/html/guide/topics/resources/available-resources.jd b/docs/html/guide/topics/resources/available-resources.jd
index 19babee..db1bf8d 100644
--- a/docs/html/guide/topics/resources/available-resources.jd
+++ b/docs/html/guide/topics/resources/available-resources.jd
@@ -29,6 +29,7 @@ Saved in {@code res/color/} and accessed from the {@code R.color} class.</dd>
<dt><a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a></dt>
<dd>Define various graphics with bitmaps or XML.<br/>
Saved in {@code res/drawable/} and accessed from the {@code R.drawable} class.</dd>
+
<dt><a href="{@docRoot}guide/topics/resources/layout-resource.html">Layout Resource</a></dt>
<dd>Define the layout for your application UI.<br/>
Saved in {@code res/layout/} and accessed from the {@code R.layout} class.</dd>
diff --git a/docs/html/guide/topics/resources/providing-resources.jd b/docs/html/guide/topics/resources/providing-resources.jd
index 6d9527f..98e7c96 100644
--- a/docs/html/guide/topics/resources/providing-resources.jd
+++ b/docs/html/guide/topics/resources/providing-resources.jd
@@ -60,18 +60,24 @@ MyProject/
MyActivity.java </span>
res/
drawable/ <span style="color:black">
- icon.png </span>
+ graphic.png </span>
layout/ <span style="color:black">
main.xml
info.xml</span>
+ mipmap/ <span style="color:black">
+ icon.png </span>
values/ <span style="color:black">
strings.xml </span>
</pre>
<p>As you can see in this example, the {@code res/} directory contains all the resources (in
-subdirectories): an image resource, two layout resources, and a string resource file. The resource
+subdirectories): an image resource, two layout resources, {@code mipmap/} directories for launcher
+icons, and a string resource file. The resource
directory names are important and are described in table 1.</p>
+<p class="note"><strong>Note:</strong> For more information about using the mipmap folders, see
+<a href="{@docRoot}tools/project/index.html#mipmap">Managing Projects Overview</a>.</p>
+
<p class="table-caption" id="table1"><strong>Table 1.</strong> Resource directories
supported inside project {@code res/} directory.</p>
@@ -104,6 +110,7 @@ State List Resource</a></td>
<tr>
<td><code>drawable/</code></td>
+
<td><p>Bitmap files ({@code .png}, {@code .9.png}, {@code .jpg}, {@code .gif}) or XML files that
are compiled into the following drawable resource subtypes:</p>
<ul>
@@ -119,6 +126,13 @@ are compiled into the following drawable resource subtypes:</p>
</tr>
<tr>
+ <td><code>mipmap/</code></td>
+ <td>Drawable files for different launcher icon densities. For more information on managing
+ launcher icons with {@code mipmap/} folders, see
+ <a href="{@docRoot}tools/project/index.html#mipmap">Managing Projects Overview</a>.</td>
+ </tr>
+
+ <tr>
<td><code>layout/</code></td>
<td>XML files that define a user interface layout.
See <a href="layout-resource.html">Layout Resource</a>.</td>
diff --git a/docs/html/guide/topics/ui/notifiers/notifications.jd b/docs/html/guide/topics/ui/notifiers/notifications.jd
index e47c77e..976115e 100644
--- a/docs/html/guide/topics/ui/notifiers/notifications.jd
+++ b/docs/html/guide/topics/ui/notifiers/notifications.jd
@@ -663,20 +663,21 @@ mNotificationManager.notify(id, builder.build());
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Creates an Intent for the Activity
Intent notifyIntent =
- new Intent(new ComponentName(this, ResultActivity.class));
+ new Intent(this, ResultActivity.class);
// Sets the Activity to start in a new, empty task
-notifyIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);
+notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
+ | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Creates the PendingIntent
-PendingIntent notifyIntent =
+PendingIntent notifyPendingIntent =
PendingIntent.getActivity(
this,
0,
- notifyIntent
+ notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
// Puts the PendingIntent into the notification builder
-builder.setContentIntent(notifyIntent);
+builder.setContentIntent(notifyPendingIntent);
// Notifications are issued by sending them to the
// NotificationManager system service.
NotificationManager mNotificationManager =
@@ -715,7 +716,7 @@ mNotificationManager.notify(id, builder.build());
<h3 id="FixedProgress">Displaying a fixed-duration progress indicator</h3>
<p>
To display a determinate progress bar, add the bar to your notification by calling
- {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress()
+ {@link android.support.v4.app.NotificationCompat.Builder#setProgress
setProgress(max, progress, false)} and then issue the notification. As your operation proceeds,
increment <code>progress</code>, and update the notification. At the end of the operation,
<code>progress</code> should equal <code>max</code>. A common way to call
@@ -727,7 +728,7 @@ mNotificationManager.notify(id, builder.build());
You can either leave the progress bar showing when the operation is done, or remove it. In
either case, remember to update the notification text to show that the operation is complete.
To remove the progress bar, call
- {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress()
+ {@link android.support.v4.app.NotificationCompat.Builder#setProgress
setProgress(0, 0, false)}. For example:
</p>
<pre>
@@ -783,8 +784,8 @@ new Thread(
<p>
Issue the notification at the beginning of the operation. The animation will run until you
modify your notification. When the operation is done, call
- {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress()
- setProgress(0, 0, false)} and then update the notification to remove the activity indicator.
+ {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress(0, 0, false)}
+ and then update the notification to remove the activity indicator.
Always do this; otherwise, the animation will run even when the operation is complete. Also
remember to change the notification text to indicate that the operation is complete.
</p>
diff --git a/docs/html/images/exoplayer/adaptive-streaming.png b/docs/html/images/exoplayer/adaptive-streaming.png
index 9fc650c..50eee70 100644
--- a/docs/html/images/exoplayer/adaptive-streaming.png
+++ b/docs/html/images/exoplayer/adaptive-streaming.png
Binary files differ
diff --git a/docs/html/images/opengl/ogl-triangle-projected.png b/docs/html/images/opengl/ogl-triangle-projected.png
index 4b18b98..a561bc5 100644
--- a/docs/html/images/opengl/ogl-triangle-projected.png
+++ b/docs/html/images/opengl/ogl-triangle-projected.png
Binary files differ
diff --git a/docs/html/images/opengl/ogl-triangle-touch.png b/docs/html/images/opengl/ogl-triangle-touch.png
index 8323dd9..67c4466 100644
--- a/docs/html/images/opengl/ogl-triangle-touch.png
+++ b/docs/html/images/opengl/ogl-triangle-touch.png
Binary files differ
diff --git a/docs/html/images/opengl/ogl-triangle.png b/docs/html/images/opengl/ogl-triangle.png
index 66047ab..f51c0c6 100644
--- a/docs/html/images/opengl/ogl-triangle.png
+++ b/docs/html/images/opengl/ogl-triangle.png
Binary files differ
diff --git a/docs/html/images/tools/projectview-p1.png b/docs/html/images/tools/projectview-p1.png
new file mode 100644
index 0000000..f5fae63
--- /dev/null
+++ b/docs/html/images/tools/projectview-p1.png
Binary files differ
diff --git a/docs/html/images/tools/projectview-p2.png b/docs/html/images/tools/projectview-p2.png
new file mode 100644
index 0000000..9e52540
--- /dev/null
+++ b/docs/html/images/tools/projectview-p2.png
Binary files differ
diff --git a/docs/html/images/tools/studio-mipmap-folders.png b/docs/html/images/tools/studio-mipmap-folders.png
new file mode 100644
index 0000000..3e99180
--- /dev/null
+++ b/docs/html/images/tools/studio-mipmap-folders.png
Binary files differ
diff --git a/docs/html/images/tools/studio-project-layout.png b/docs/html/images/tools/studio-project-layout.png
index 880c233..7339c3f 100644
--- a/docs/html/images/tools/studio-project-layout.png
+++ b/docs/html/images/tools/studio-project-layout.png
Binary files differ
diff --git a/docs/html/images/transitions/transition_sample_video.mp4 b/docs/html/images/transitions/transition_sample_video.mp4
new file mode 100644
index 0000000..37ae685
--- /dev/null
+++ b/docs/html/images/transitions/transition_sample_video.mp4
Binary files differ
diff --git a/docs/html/images/transitions/transition_sample_video.ogv b/docs/html/images/transitions/transition_sample_video.ogv
new file mode 100644
index 0000000..5598814
--- /dev/null
+++ b/docs/html/images/transitions/transition_sample_video.ogv
Binary files differ
diff --git a/docs/html/images/transitions/transition_sample_video.webm b/docs/html/images/transitions/transition_sample_video.webm
new file mode 100644
index 0000000..346ba8c
--- /dev/null
+++ b/docs/html/images/transitions/transition_sample_video.webm
Binary files differ
diff --git a/docs/html/images/transitions/transitions_diagram.png b/docs/html/images/transitions/transitions_diagram.png
new file mode 100644
index 0000000..9363940
--- /dev/null
+++ b/docs/html/images/transitions/transitions_diagram.png
Binary files differ
diff --git a/docs/html/images/tv/app-browse.png b/docs/html/images/tv/app-browse.png
new file mode 100644
index 0000000..7670713
--- /dev/null
+++ b/docs/html/images/tv/app-browse.png
Binary files differ
diff --git a/docs/html/images/tv/card-view.png b/docs/html/images/tv/card-view.png
new file mode 100644
index 0000000..5e907de
--- /dev/null
+++ b/docs/html/images/tv/card-view.png
Binary files differ
diff --git a/docs/html/images/tv/deep-link.png b/docs/html/images/tv/deep-link.png
new file mode 100644
index 0000000..8f2f788
--- /dev/null
+++ b/docs/html/images/tv/deep-link.png
Binary files differ
diff --git a/docs/html/sdk/index.jd b/docs/html/sdk/index.jd
index d712196..1100964 100644
--- a/docs/html/sdk/index.jd
+++ b/docs/html/sdk/index.jd
@@ -482,14 +482,14 @@ rendering. You can then configure your project to use Java Development Kit (JDK)
<ul>
<li>GNOME or KDE desktop</li>
-<li>GNU C Library (glibc) 2.11 or later</li>
+<li>GNU C Library (glibc) 2.15 or later</li>
<li>2 GB RAM minimum, 4 GB RAM recommended</li>
<li>400 MB hard disk space</li>
<li>At least 1 GB for Android SDK, emulator system images, and caches</li>
<li>1280 x 800 minimum screen resolution</li>
<li>Oracle&reg; Java Development Kit (JDK) 7 </li>
</ul>
-<p>Tested on Ubuntu&reg; 12.04, Precise Pangolin (64-bit distribution capable of running
+<p>Tested on Ubuntu&reg; 14.04, Trusty Tahr (64-bit distribution capable of running
32-bit applications).</p>
diff --git a/docs/html/sdk/installing/create-project.jd b/docs/html/sdk/installing/create-project.jd
index 5082537..68fd572 100644
--- a/docs/html/sdk/installing/create-project.jd
+++ b/docs/html/sdk/installing/create-project.jd
@@ -71,7 +71,7 @@ of your project.</p>
<h3 id="Step2SelectFormFactor">Step 2: Select Form Factors and API Level</h2>
<p>The next window lets you select the form factors supported by your app, such as phone, tablet,
-TV, Wear, and Google Glass. The selected form factors become the application modules witin the
+TV, Wear, and Google Glass. The selected form factors become the application modules within the
project. For each form factor, you can also select the API Level for that app. To get more information,
click <strong>Help me choose</strong>.</p>
@@ -220,7 +220,7 @@ with complete source files for each of them as shown in figure 6.</p>
along with the other modules. </p>
<p> You can easily change an existing application module to a library module by changing the
- plugin assignment in the <strong>build.gradle</strong> file to <em>com.android.libary</em>.</p>
+ plugin assignment in the <strong>build.gradle</strong> file to <em>com.android.library</em>.</p>
<pre>
apply plugin: 'com.android.application'
@@ -287,7 +287,7 @@ file will override any shared library resources declared in the manifest file.</
<ol>
<li>Make sure that both the module library and the application module that depends on it are
- in your proejct. If one of the modules is missing, import it into your project.</li>
+ in your project. If one of the modules is missing, import it into your project.</li>
<li>In the project view, right-click the dependent module and select
<strong>Open</strong> > <strong>Module Settings</strong>.</li>
@@ -359,39 +359,38 @@ Android project view:</p>
per resource type.</li>
</ul>
-<div style="float:right;margin-left:30px;width:240px">
-<img src="{@docRoot}images/tools/projectview01.png" alt="" width="220" height="264"/>
-<p class="img-caption"><strong>Figure 9:</strong> Show the Android project view.</p>
-</div>
-<h2 id="enable-view">Enable and use the Android Project View</h2>
+<h2 id="enable-view">Use the Android Project View</h2>
-<p>The Android project view is not yet enabled by default. To show the Android project view,
-click <strong>Project</strong> and select <strong>Android</strong>, as shown in figure 9.</p>
-
-<p>The Android project view shows all the build files at the top level of the project hierarchy
-under <strong>Gradle Scripts</strong>. Each project module appears as a folder at the top
-level of the project hierarchy and contains these three elements at the top level:</p>
+<p>The <em>Android</em> project view is enabled by default and shows all the build files at
+the top level of the project hierarchy under <strong>Gradle Scripts</strong>. The project module
+appears as a folder at the top level of the project hierarchy and contains these three elements
+at the top level:</p>
<ul>
-<li><code>java/</code> - Source files for the module.</li>
<li><code>manifests/</code> - Manifest files for the module.</li>
+<li><code>java/</code> - Source files for the module.</li>
<li><code>res/</code> - Resource files for the module.</li>
</ul>
-<p>Figure 10 shows how the Android project view groups all the instances of the
+<p>Notice how the Android project view groups all instances of the
<code>ic_launcher.png</code> resource for different screen densities under the same element.</p>
<p class="note"><strong>Note:</strong> The Android project view shows a hierarchy that helps you
work with Android projects by providing a flattened structure that highlights the most commonly
used files while developing Android applications. However, the project structure on disk differs
-from this representation.</p>
+from this representation and maintains the traditional project structure.</p>
+
+<img src="{@docRoot}images/tools/projectview-p1.png" alt="" style="width:240px" "/>
+&nbsp;&nbsp;&nbsp;
+<img src="{@docRoot}images/tools/projectview-p2.png" alt="" style="width:240px" " />
+<p class="img-caption"><strong>Figure 10:</strong> Android and Traditional project view </p>
+
+
+
+
-<img src="{@docRoot}images/tools/projectview03.png" alt=""
- style="margin-top:10px" width="650" height="508"/>
-<p class="img-caption"><strong>Figure 10:</strong> The traditional project view (left) and the
-Android project view (right).</p>
diff --git a/docs/html/tools/building/plugin-for-gradle.jd b/docs/html/tools/building/plugin-for-gradle.jd
index 77cbfda..54a03fd 100644
--- a/docs/html/tools/building/plugin-for-gradle.jd
+++ b/docs/html/tools/building/plugin-for-gradle.jd
@@ -321,7 +321,7 @@ logic inside Gradle build files instead.</p>
machine and on other machines where Android Studio is not installed.</p>
<p class="caution"><strong>Caution:</strong> When you create a project, only use the Gradle wrapper
-scripts and JAR from a trusted source, such as those generated by Android Studio. /p>
+scripts and JAR from a trusted source, such as those generated by Android Studio. </p>
<h2 id="buildVariants"> Build variants</h2>
diff --git a/docs/html/tools/devices/emulator.jd b/docs/html/tools/devices/emulator.jd
index 42240b9..5bdd4e2 100644
--- a/docs/html/tools/devices/emulator.jd
+++ b/docs/html/tools/devices/emulator.jd
@@ -122,7 +122,7 @@ machine.</p>
mobile devices, including: </p>
<ul>
- <li>An ARMv5 CPU and the corresponding memory-management unit (MMU)</li>
+ <li>An ARMv5, ARMv7, or x86 CPU</li>
<li>A 16-bit LCD display</li>
<li>One or more keyboards (a Qwerty-based keyboard and associated Dpad/Phone
buttons)</li>
diff --git a/docs/html/tools/projects/index.jd b/docs/html/tools/projects/index.jd
index 5f4f2cc..8665479 100644
--- a/docs/html/tools/projects/index.jd
+++ b/docs/html/tools/projects/index.jd
@@ -1,4 +1,6 @@
page.title=Managing Projects Overview
+meta.tags="project, mipmap"
+page.tags="project", "mipmap"
@jd:body
<div id="qv-wrapper">
@@ -8,7 +10,9 @@ page.title=Managing Projects Overview
<ol>
<li><a href="#ProjectFiles">Android Project Files</a></li>
<li><a href="#ApplicationModules">Android Application Modules</a></li>
-
+ <ol>
+ <li><a href="#mipmap">Managing Launcher Icons as mipmap Resources</a></li>
+ </ol>
<li><a href="#LibraryModules">Library Modules</a>
<ol>
<li><a href="#considerations">Development considerations</a></li>
@@ -230,7 +234,18 @@ project and override similar module file settings.</p>
focused). See the <a href=
"{@docRoot}guide/topics/resources/drawable-resource.html">Drawable</a> resource type.</dd>
- <dt><code>layout/</code></dt>
+
+ <dt><code>mipmap/</code></dt>
+
+ <dd>For app launcher icons. The Android system retains the resources in this folder
+ (and density-specific folders such as mipmap-xxxhdpi) regardless of the screen resolution
+ of the device where your app is installed. This behavior allows launcher apps to pick
+ the best resolution icon for your app to display on the home screen. For more information
+ about using the <code>mipmap</code> folders, see
+ <a href="#mipmap">Managing Launcher Icons as mipmap Resources</a>. </p>
+
+
+ <dt><code>layout/</code></dt>
<dd>XML files that are compiled into screen layouts (or part of a screen). See the <a href=
"{@docRoot}guide/topics/resources/layout-resource.html">Layout</a> resource type.</dd>
@@ -304,6 +319,46 @@ project and override similar module file settings.</p>
+<h2 id="mipmap">Managing Launcher Icons as mipmap Resources</h2>
+
+<p>Different home screen launcher apps on different devices show app launcher icons at various
+resolutions. When app resource optimization techniques remove resources for unused
+screen densities, launcher icons can wind up looking fuzzy because the launcher app has to upscale
+a lower-resolution icon for display. To avoid these display issues, apps should use the
+<code>mipmap/</code> resource folders for launcher icons. The Android system
+preserves these resources regardless of density stripping, and ensures that launcher apps can
+pick icons with the best resolution for display. </p>
+
+<p>Make sure launcher apps show a high-resolution icon for your app by moving all densities of your
+launcher icons to density-specific <code>res/mipmap/</code> folders
+(for example <code>res/mipmap-mdpi/</code> and <code>res/mipmap-xxxhdpi/</code>). The
+<code>mipmap/</code> folders replace the <code>drawable/</code> folders for launcher icons. For
+xxhpdi launcher icons, be sure to add the higher resolution xxxhdpi versions of the
+icons to enhance the visual experience of the icons on higher resolution devices.</p>
+
+<p class="note"><strong>Note:</strong> Even if you build a single APK for all devices, it is still
+best practice to move your launcher icons to the <code>mipmap/</code> folders.</p>
+
+
+<h3>Manifest update</h3>
+
+<p>When you move your launcher icons to the <code>mipmap-[density]</code> folders, change the
+launcher icon references in the <code>AndroidManifest.xml</code> file so your manifest references
+the <code>mipmap/</code> location. This example changes the manifest file to reference the
+<code>ic_launcher</code> icon in the <code>mipmap/</code> folder. </p>
+
+<pre>
+...
+&lt;application android:name="ApplicationTitle"
+ android:label="@string/app_label"
+ android:icon="@mipmap/ic_launcher" &gt;
+ ...
+</pre>
+
+
+
+
+
<h2 id="LibraryModules">Library Module</h2>
<div class="sidebox-wrapper">
diff --git a/docs/html/tools/revisions/gradle-plugin.jd b/docs/html/tools/revisions/gradle-plugin.jd
new file mode 100644
index 0000000..23170e1
--- /dev/null
+++ b/docs/html/tools/revisions/gradle-plugin.jd
@@ -0,0 +1,153 @@
+page.title=Android Plugin for Gradle Release Notes
+
+@jd:body
+
+<div id="qv-wrapper">
+<div id="qv">
+
+ <h2>See also</h2>
+ <ol>
+ <li><a href="{@docRoot}sdk/installing/studio-build.html">Build System Overview</a></li>
+ <li><a href="{@docRoot}tools/building/plugin-for-gradle.html">Android Plugin for Gradle</a></li>
+ </ol>
+
+</div>
+</div>
+
+
+<p>The Android build system uses the Android Plugin for Gradle to support building Android
+applications with the <a href="http://www.gradle.org/">Gradle</a> build toolkit. The plugin runs
+independent of Android Studio so the plugin and the Gradle build system can be updated
+independently of Android Studio.</p>
+
+<p class="note"><strong>Note:</strong> When you update Android Studio or open a project in a
+previous version of Android Studio, Android Studio prompts you to automatically update the plugin
+and Gradle to the latest available versions. You can choose to accept these updates based
+on your project's build requirements. </p>
+
+
+<h2 id="revisions">Revisions</h2>
+
+<p>The sections below provide notes about successive releases of
+the Android Plugin for Gradle, as denoted by revision number. To determine what revision of the
+plugin you are using, check the version declaration in the project-level
+<strong>build.gradle</strong> file. </p>
+
+<p>For a summary of known issues in Android Plugin for Gradle, see <a
+href="http://tools.android.com/knownissues">http://tools.android.com/knownissues</a>.</p>
+
+
+<div class="toggle-content opened">
+ <p><a href="#" onclick="return toggleContent(this)">
+ <img src="{@docRoot}assets/images/triangle-opened.png" class="toggle-content-img"
+ alt=""/>Android Plugin for Gradle, Revision 1.1</a> <em>(February 2015)</em>
+ </p>
+
+ <div class="toggle-content-toggleme">
+
+ <dl>
+ <dt>Dependencies:</dt>
+
+ <dd>
+ <ul>
+ <li>Gradle 2.2.1 or higher.</li>
+ <li>Build Tools 21.1.1 or higher.</li>
+ </ul>
+ </dd>
+
+ <dt>General Notes:</dt>
+ <dd>
+ <ul>
+ <li>Fixed issue with Gradle build failure when accessing the
+ <code>extractReleaseAnnotations</code> module.
+ (<a href="http://b.android.com/81638">Issue 81638</a>).</li>
+ <li>Fixed debugging issue when displaying method input parameters at breakpoints.
+ (<a href="http://b.android.com/82031">Issue 82031</a>).</li>
+ <li>Fixed manifest merger issues when importing libraries with a <code>targetSdkVersion</code>
+ less than 16.</li>
+ <li>Fixed density ordering issue when using Android Studio with JDK 8.</li>
+ </ul>
+ </dd>
+ </div>
+</div>
+
+
+
+<div class="toggle-content closed">
+ <p><a href="#" onclick="return toggleContent(this)">
+ <img src="{@docRoot}assets/images/triangle-closed.png" class="toggle-content-img"
+ alt=""/>Android Plugin for Gradle, Revision 1.0</a> <em>(December 2014)</em>
+ </p>
+
+ <div class="toggle-content-toggleme">
+
+ <dl>
+ <dt>Dependencies:</dt>
+
+ <dd>
+ <ul>
+ <li>Gradle 2.2.1 or higher.</li>
+ <li>Build Tools 21.1.1 or higher.</li>
+ </ul>
+ </dd>
+
+ <dt>General Notes:</dt>
+ <dd>
+ <ul>
+ <li>Initial plugin release.</li>
+ </ul>
+ </dd>
+ </div>
+</div>
+
+
+
+
+<h2>Updating the Android Plugin for Gradle Version</h2>
+<p>The Android Plugin for Gradle version is specified in the
+<strong>File &gt; Project Structure</strong> menu or the project-level
+<code>build.gradle</code> file. The plugin version applies to all modules built in that
+Android Studio project. This example updates the Android Plugin for Gradle to version 1.1:
+<pre>
+...
+ dependencies {
+ classpath 'com.android.tools.build:gradle:1.1'
+ }
+...
+</pre>
+
+
+<p class="caution"><strong>Caution:</strong> You should not use dynamic dependencies (+) in
+version numbers. Using this feature can cause unexpected version updates and difficulty
+resolving version differences.
+</p>
+
+<p>If you're building with Gradle but using not Android Studio, the build process downloads the
+latest Android Plugin for Gradle plugin when it runs. </p>
+
+
+
+<h2>Updating the Gradle Version </h2>
+
+<p>Android Studio requires Gradle version 2.2.1 or later. To view and
+update the Gradle version, edit the Gradle distribution reference in the
+<code>gradle/wrapper/gradle-wrapper.properties</code> file. This example shows the
+Android Plugin for Gradle version set to 2.2.1.</p>
+
+<pre>
+...
+distributionUrl=http\://services.gradle.org/distributions/gradle-2.2.1-all.zip
+...
+</pre>
+
+
+
+
+<p>For more details about the supported Android Plugin for Gradle properties and syntax, click
+the link to the
+<a href="{@docRoot}tools/building/plugin-for-gradle.html">Plugin Language Reference</a>.</p>
+
+
+
+
+
diff --git a/docs/html/tools/revisions/studio.jd b/docs/html/tools/revisions/studio.jd
index 3806933..af25d9c 100644
--- a/docs/html/tools/revisions/studio.jd
+++ b/docs/html/tools/revisions/studio.jd
@@ -29,7 +29,7 @@ everything you need to begin developing Android apps:</p>
<p>For an introduction to Android Studio, read the
<a href="{@docRoot}tools/studio/index.html">Android Studio</a> guide.</p>
-<p>Periodic updates are pushed to Android Studio without requiring you to update from here. To
+<p>Periodic updates are pushed to Android Studio without requiring you to update. To
manually check for updates, select <strong>Help > Check for updates</strong> (on Mac, select
<strong>Android Studio > Check for updates</strong>).</p>
@@ -43,6 +43,33 @@ Android Studio, as denoted by revision number. </p>
<div class="toggle-content opened">
<p><a href="#" onclick="return toggleContent(this)">
<img src="{@docRoot}assets/images/triangle-opened.png" class="toggle-content-img"
+ alt=""/>Android Studio v1.1</a> <em>(February 2015)</em>
+ </p>
+
+ <div class="toggle-content-toggleme">
+ <p>Various fixes and enhancements:</p>
+ <ul>
+ <li>Added support for the <a href="{@docRoot}design/wear/index.html">Android Wear</a> watch
+ template. </li>
+ <li>Modified new project and module creation to include
+ <a href="{@docRoot}tools/projects/index.html#mipmap"><code>res/mipmap</code></a> folders for
+ density-specific launcher icons. These <code>res/mipmap</code> folders replace the
+ <a href="{@docRoot}guide/topics/resources/drawable-resource.html"><code>res/drawable</code></a>
+ folders for launcher icons. </li>
+ <li>Updated launcher icons to have a
+ <a href="{@docRoot}design/material/index.html">Material Design</a> look and added an
+ <code>xxxhdpi</code> launcher icon. </li>
+ <li>Added and enhanced <a href="{@docRoot}tools/help/lint.html"><code>lint</code></a> checks
+ for region and language combinations, launcher icons, resource names, and other common
+ code problems.</li>
+ <li>Added support for Best Current Practice (BCP) language tag 47. </li>
+ </div>
+</div>
+
+
+<div class="toggle-content closed">
+ <p><a href="#" onclick="return toggleContent(this)">
+ <img src="{@docRoot}assets/images/triangle-closed.png" class="toggle-content-img"
alt=""/>Android Studio v1.0.1</a> <em>(December 2014)</em>
</p>
diff --git a/docs/html/tools/studio/index.jd b/docs/html/tools/studio/index.jd
index 42ab89c..11c1c74 100644
--- a/docs/html/tools/studio/index.jd
+++ b/docs/html/tools/studio/index.jd
@@ -10,6 +10,7 @@ page.title=Android Studio Overview
<li><a href="#build-system">Android Build System</a></li>
<li><a href="#debug-perf">Debug and Performance</a></li>
<li><a href="#install-updates">Installation, Setup, and Update Management</a></li>
+ <li><a href="#proxy">HTTP Proxy Settings</a></li>
<li><a href="#other">Other Highlights</a></li>
@@ -64,7 +65,7 @@ Studio</a>.</p>
<h3 id="project-view"><em>Android</em> Project View</h3>
<p>By default, Android Studio displays your profile files in the <em>Android</em> project view. This
view shows a flattened version of your project's structure that provides quick access to the key
-source files of Android projects and helps you work with the new
+source files of Android projects and helps you work with the
<a href="{@docRoot}sdk/installing/studio-build.html">Gradle-based build system</a>.
The Android project view:</p>
@@ -101,7 +102,7 @@ the <strong>Project</strong drop-down. </p>
-<h3>New Project and Directory Structure</h3>
+<h3>Android Studio Project and Directory Structure</h3>
<p>When you use the <em>Project</em> view of a new project in Android Studio, you
should notice that the project structure appears different than you may be used to in Eclipse. Each
instance of Android Studio contains a project with one or more application modules. Each
@@ -119,6 +120,7 @@ specification and the files under {@code src/androidTest} directory for test cas
<a href="{@docRoot}tools/projects/index.html">Managing Projects</a>.</p>
+
<h3>Creating new files</h3>
<p>You can quickly add new code and resource files by clicking the appropriate directory in the
<strong>Project</strong> pane and pressing <code>ALT + INSERT</code> on Windows and Linux or
@@ -249,23 +251,15 @@ memory the connected device is using. With your app running on a device or emula
<strong>Memory Monitor</strong> tab in the lower right corner to launch the memory monitor. </p>
<img src="{@docRoot}images/tools/studio-memory-monitor.png" />
- <p class="img-caption"><strong>Figure 4.</strong> Memory Monitor</p>
+ <p class="img-caption"><strong>Figure 5.</strong> Memory Monitor</p>
-<h3> New Lint inspections</h3>
-<p>Lint has several new checks to ensure:
-<ul>
- <li><code> Cipher.getInstance()</code> is used with safe values</li>
- <li>In custom Views, the associated declare-styleable for the custom view uses the same
- base name as the class name.</li>
- <li>Security check for fragment injection.</li>
- <li>Where ever property assignment no longer works as expected.</li>
- <li>Gradle plugin version is compatible with the SDK.</li>
- <li>Right to left validation </li>
- <li>Required API version</li>
- <li>many others</li>
-</ul>
+<h3> Lint inspections</h3>
+<p>The Android {@code lint} tool is a static code analysis tool that checks your Android project
+source files for potential bugs and optimization improvements. Choose the <strong>Analyze &gt;
+Inspect Code</strong> to manually run the inspections. The {@code lint} settings icon in the
+Inspection display provides a complete list of the current inspections.</p>
<p>Hovering over a Lint error displays the full issue explanation inline for easy error
resolution. There is also a helpful hyperlink at the end of the error message for additional
@@ -294,17 +288,17 @@ build.gradle file. </p>
<p>Android Studio allows you to work with layouts in both a <em>Design View</em> </p>
<p><img src="{@docRoot}images/tools/studio-helloworld-design.png" alt="" />
</p>
- <p class="img-caption"><strong>Figure 5.</strong> Hello World App with Design View</p>
+ <p class="img-caption"><strong>Figure 6.</strong> Hello World App with Design View</p>
<p>and a <em>Text View</em>. </p>
<p><img src="{@docRoot}images/tools/studio-helloworld-text.png" alt="" />
- <pclass="img-caption"><strong>Figure 6.</strong> Hello World App with Text View</p>
+ <pclass="img-caption"><strong>Figure 7.</strong> Hello World App with Text View</p>
<p>Easily select and preview layout changes for different device images, display
densities, UI modes, locales, and Android versions (multi-API version rendering).
<p><img src="{@docRoot}images/tools/studio-api-version-rendering.png" /></p>
- <p class="img-caption"><strong>Figure 7.</strong> API Version Rendering</p>
+ <p class="img-caption"><strong>Figure 8.</strong> API Version Rendering</p>
<p>From the Design View, you can drag and drop elements from the Palette to the Preview or
@@ -341,18 +335,18 @@ the wizard updates your system image and emulation requirements, such GPU, and t
an optimized default Android Virtual Device (AVD) based on Android 5 (Lollipop) for speedy and
reliable emulation. </p>
<p><img src="{@docRoot}images/tools/studio-setup-wizard.png" /></p>
-<p class="img-caption"><strong>Figure 8.</strong> Setup Wizard</p>
+<p class="img-caption"><strong>Figure 9.</strong> Setup Wizard</p>
<h3>Expanded template and form factor support</h3>
-<p>Android Studio supports new templates for Google Services and expands the available device
+<p>Android Studio supports templates for Google Services and expands the available device
types. </p>
<h4> Android Wear and TV support</h4>
<p>For easy cross-platform development, the Project Wizard provides new templates for
creating your apps for Android Wear and TV. </p>
<p><img src="{@docRoot}images/tools/studio-tvwearsupport.png" />
- <p class="img-caption"><strong>Figure 9.</strong> New Form Factors</p>
+ <p class="img-caption"><strong>Figure 10.</strong> Supported Form Factors</p>
<p>During app creation, the Project Wizard also displays an API Level dialog to help you choose
the best <em>minSdkVersion</em> for your project.</p>
@@ -362,7 +356,7 @@ types. </p>
and create a cloud end-point is as easy as selecting <em>File > New Module > App Engine Java
Servlet Module</em> and specifying the module, package, and client names. </p>
<p><img src="{@docRoot}images/tools/studio-cloudmodule.png" /></p>
- <p class="img-caption"><strong>Figure 10.</strong> Setup Wizard</p>
+ <p class="img-caption"><strong>Figure 11.</strong> Setup Wizard</p>
@@ -386,6 +380,120 @@ code-level preference:
+<h2 id="proxy">Proxy Settings</h2>
+<p>Proxies serve as intermediary connection points between HTTP clients and web servers that add
+security and privacy to internet connections.</p>
+
+<p>To support running Android Studio behind a firewall, set the proxy settings for the
+Android Studio IDE and the SDK Manager. Use the Android Studio IDE HTTP Proxy settings page to set
+the HTTP proxy settings for Android Studio. The SDK Manager has a separate HTTP Proxy settings
+page.</p>
+
+<p>When running the Android Plugin for Gradle from the command line or on machines where
+Android Studio is not installed, such as continuous integration servers, set the proxy settings
+in the Gradle build file.</p>
+
+<p class="note"><strong>Note:</strong> After the initial installation of the Android Studio bundle,
+Android Studio can run with internet access or off-line. However, Android Studio requires an
+internet connection for Setup Wizard synchronization, 3rd-party library access, access to remote
+repositories, Gradle initialization and synchronization, and Android Studio version updates.</p>
+
+
+<h3>Setting up the Android Studio Proxy</h3>
+<p>Android Studio supports HTTP proxy settings so you can run Android Studio behind a firewall or
+secure network. To set the HTTP proxy settings in Android Studio:</p>
+<ol>
+ <li>From the main menu choose <strong>File &gt; Settings &gt; IDE Setting -- HTTP Proxy</strong>.
+
+<li>In Android Studio, open the IDE Settings dialog.
+ <ul>
+ <li>On Windows and Linux, choose
+ <strong>File &gt; Settings &gt; IDE Setting -- HTTP Proxy</strong>. </li>
+ <li>On Mac, choose
+ <strong>Android Studio &gt; Preferences &gt; IDE Setting -- HTTP Proxy</strong>. </li>
+ </ul>
+ The HTTP Proxy page appears.</li>
+ <li>Select <strong>auto-detection</strong> to use an auto-configuration URL to configure the
+ proxy settings or <strong>manual</strong> to enter each of the settings. For a detailed explanation
+ of these settings, see
+ <a href="https://www.jetbrains.com/idea/help/http-proxy.html">HTTP Proxy</a>. </li>
+ <li>Click <strong>Apply</strong> to enable the proxy settings. </li>
+</ol>
+
+<h3>Android Plugin for Gradle HTTP proxy settings</h3>
+When running the Android Plugin from the command line or on machines where Android Studio is not
+installed, set the Android Plugin for Gradle proxy settings in the Gradle build file.</p>
+
+<p>For application-specific HTTP proxy settings, set the proxy settings in the
+<strong>build.gradle</strong> file as required for each application module.</p>
+<pre>
+apply plugin: 'com.android.application'
+
+android {
+ ...
+
+ defaultConfig {
+ ...
+ systemProp.http.proxyHost=proxy.company.com
+ systemProp.http.proxyPort=443
+ systemProp.http.proxyUser=userid
+ systemProp.http.proxyPassword=password
+ systemProp.http.auth.ntlm.domain=domain
+ }
+ ...
+}
+</pre>
+
+
+
+<p>For project-wide HTTP proxy settings, set the proxy settings in the
+<code>gradle/gradle.properties</code> file. </p>
+
+<pre>
+# Project-wide Gradle settings.
+...
+
+systemProp.http.proxyHost=proxy.company.com
+systemProp.http.proxyPort=443
+systemProp.http.proxyUser=username
+systemProp.http.proxyPassword=password
+systemProp.http.auth.ntlm.domain=domain
+
+systemProp.https.proxyHost=proxy.company.com
+systemProp.https.proxyPort=443
+systemProp.https.proxyUser=username
+systemProp.https.proxyPassword=password
+systemProp.https.auth.ntlm.domain=domain
+
+...
+</pre>
+
+
+<p>For information about using Gradle properties for proxy settings, see the
+ <a href="http://www.gradle.org/docs/current/userguide/build_environment.html">Gradle User Guide</a>.</p>
+
+<p class="note"><strong>Note:</strong> When using Android Studio, the settings in the Android
+Studio IDE HTTP proxy settings page override the HTTP proxy settings in the
+<strong>gradle.properties</strong> file.</p>
+
+
+
+<h3>SDK Manager HTTP Proxy Settings </h3>
+<p>SDK Manager proxy settings enable proxy internet access for Android package and library
+updates from SDK Manager packages. </p>
+
+<p>To set the SDK Manager settings for proxy internet access, start the SDK Manager and open the
+SDK Manager page. </p>
+
+<ul>
+ <li>On Windows, select <strong>Tools &gt; Options</strong> from the menu bar. </li>
+ <li>On Mac and Linux, choose <strong>Tools &gt; Options</strong> from the system menu bar. </li>
+ </ul>
+
+<p>The Android SDK Manager page appears. Enter the settings and click <strong>Apply</strong>. </p>
+
+
+
<h2 id="other">Other Highlights</h2>
<h3> Translation Editor</h3>
@@ -399,14 +507,14 @@ into your project. </p>
<strong>Open Editor</strong> link. </p>
<img src="{@docRoot}images/tools/studio-translationeditoropen.png" />
- <p class="img-caption"><strong>Figure 11.</strong> Translation Editor</p>
+ <p class="img-caption"><strong>Figure 12.</strong> Translation Editor</p>
<h3> Editor support for the latest Android APIs</h3>
-<p>Android Studio supports the new
+<p>Android Studio supports the
<a href="{@docRoot}design/material/index.html">Material Design</a></li> themes, widgets, and
graphics, such as shadow layers and API version rendering (showing the layout across different
-UI versions). Also, the new drawable XML tags and attributes, such as &lt;ripple&gt;
+UI versions). Also, the drawable XML tags and attributes, such as &lt;ripple&gt;
and &lt;animated-selector&gt;, are supported.</p>
@@ -414,10 +522,10 @@ and &lt;animated-selector&gt;, are supported.</p>
<p>Clicking <strong>Import Samples</strong> from the <strong>File</strong> menu or Welcome page
provides seamless access to Google code samples on GitHub.</p>
<p><img src="{@docRoot}images/tools/studio-samples-githubaccess.png" /></p>
- <p class="img-caption"><strong>Figure 12.</strong> Code Sample Access</p>
+ <p class="img-caption"><strong>Figure 13.</strong> Code Sample Access</p>
<p><img src="{@docRoot}images/tools/studio-sample-in-editor.png" /></p>
- <p class="img-caption"><strong>Figure 13.</strong> Imported Code Sample</p>
+ <p class="img-caption"><strong>Figure 14.</strong> Imported Code Sample</p>
diff --git a/docs/html/tools/support-library/features.jd b/docs/html/tools/support-library/features.jd
index 079dd71..0f0a0c0 100644
--- a/docs/html/tools/support-library/features.jd
+++ b/docs/html/tools/support-library/features.jd
@@ -143,10 +143,9 @@ numbers, can cause unexpected version updates and regression incompatibilities.<
<p>The Gradle build script dependency identifier for this library is as follows:</p>
<pre>
-com.android.support:support-v4:21.0.+
+com.android.support:support-v4:21.0.0
</pre>
-<p>This dependency notation specifies the latest release version with the 21.0 prefix.</p>
<h2 id="multidex">Multidex Support Library</h2>
@@ -171,10 +170,9 @@ com.android.support:support-v4:21.0.+
</p>
<pre>
-com.android.support:multidex:1.0.+
+com.android.support:multidex:1.0.0
</pre>
-<p>This dependency notation specifies the latest release version with the 1.0 prefix.</p>
<h2 id="v7">v7 Support Libraries</h2>
@@ -226,10 +224,9 @@ com.android.support:multidex:1.0.+
<p>The Gradle build script dependency identifier for this library is as follows:</p>
<pre>
-com.android.support:appcompat-v7:21.0.+
+com.android.support:appcompat-v7:21.0.0
</pre>
-<p>This dependency notation specifies the latest release version with the 21.0 prefix.</p>
<h3 id="v7-cardview">v7 cardview library</h3>
@@ -249,10 +246,9 @@ libraries with resources</a>.</p>
<p>The Gradle build script dependency identifier for this library is as follows:</p>
<pre>
-com.android.support:cardview-v7:21.0.+
+com.android.support:cardview-v7:21.0.0
</pre>
-<p>This dependency notation specifies the latest release version with the 21.0 prefix.</p>
<h3 id="v7-gridlayout">v7 gridlayout library</h3>
@@ -271,10 +267,9 @@ com.android.support:cardview-v7:21.0.+
<p>The Gradle build script dependency identifier for this library is as follows:</p>
<pre>
-com.android.support:gridlayout-v7:21.0.+
+com.android.support:gridlayout-v7:21.0.0
</pre>
-<p>This dependency notation specifies the latest release version with the 21.0 prefix.</p>
<h3 id="v7-mediarouter">v7 mediarouter library</h3>
@@ -308,7 +303,7 @@ script dependency identifier <code>com.android.support:support-v7-mediarouter:&l
where "&lt;revision&gt;" is the minimum revision at which the library is available. For example:</p>
<pre>
-com.android.support:mediarouter-v7:21.0.+
+com.android.support:mediarouter-v7:21.0.0
</pre>
<p class="caution">The v7 mediarouter library APIs introduced in Support Library
@@ -335,11 +330,9 @@ title card.</p>
<p>The Gradle build script dependency identifier for this library is as follows:</p>
<pre>
-com.android.support:palette-v7:21.0.+
+com.android.support:palette-v7:21.0.0
</pre>
-<p>This dependency notation specifies the latest release version with the 21.0 prefix.</p>
-
<h3 id="v7-recyclerview">v7 recyclerview library</h3>
@@ -360,11 +353,9 @@ libraries with resources</a>.</p>
<p>The Gradle build script dependency identifier for this library is as follows:</p>
<pre>
-com.android.support:recyclerview-v7:21.0.+
+com.android.support:recyclerview-v7:21.0.0
</pre>
-<p>This dependency notation specifies the latest release version with the 21.0 prefix.</p>
-
<h2 id="v8">v8 Support Library</h2>
@@ -405,11 +396,9 @@ com.android.support:recyclerview-v7:21.0.+
<p>The Gradle build script dependency identifier for this library is as follows:</p>
<pre>
-com.android.support:support-v13:18.0.+
+com.android.support:support-v13:18.0.0
</pre>
-<p>This dependency notation specifies the latest release version with the 18.0 prefix.</p>
-
<h2 id="v17-leanback">v17 Leanback Library</h2>
@@ -448,9 +437,8 @@ with resources</a>. </p>
<p>The Gradle build script dependency identifier for this library is as follows:</p>
<pre>
-com.android.support:leanback-v17:21.0.+
+com.android.support:leanback-v17:21.0.0
</pre>
-<p>This dependency notation specifies the latest release version with the 21.0 prefix.</p>
diff --git a/docs/html/tools/tools_toc.cs b/docs/html/tools/tools_toc.cs
index ab6c739..62c21a6 100644
--- a/docs/html/tools/tools_toc.cs
+++ b/docs/html/tools/tools_toc.cs
@@ -249,6 +249,9 @@ class="en">Support Library</span></a></div>
<li><a href="<?cs var:toroot ?>tools/revisions/build-tools.html">
<span class="en">SDK Build Tools</span>
</a></li>
+ <li><a href="<?cs var:toroot ?>tools/revisions/gradle-plugin.html">
+ <span class="en">Android Plugin for Gradle</span>
+ </a></li>
<li><a href="<?cs var:toroot ?>tools/revisions/platforms.html">
<span class="en">SDK Platforms</span></a></li>
<li><a href="<?cs var:toroot ?>tools/sdk/eclipse-adt.html">
diff --git a/docs/html/training/articles/security-tips.jd b/docs/html/training/articles/security-tips.jd
index e05b44c..3215a0e 100644
--- a/docs/html/training/articles/security-tips.jd
+++ b/docs/html/training/articles/security-tips.jd
@@ -445,7 +445,17 @@ locally. Server-side
headers like <code>no-cache</code> can also be used to indicate that an application should
not cache particular content.</p>
-
+<p>Devices running platforms older than Android 4.4 (API level 19)
+use a version of {@link android.webkit webkit} that has a number of security issues.
+As a workaround, if your app is running on these devices, it
+should confirm that {@link android.webkit.WebView} objects display only trusted
+content. You should also use the updatable security {@link
+java.security.Provider Provider} object to make sure your app isn’t exposed to
+potential vulnerabilities in SSL, as described in <a
+href="{@docRoot}training/articles/security-gms-provider.html">Updating Your
+Security Provider to Protect Against SSL Exploits</a>. If your application must
+render content from the open web, consider providing your own renderer so
+you can keep it up to date with the latest security patches.</p>
<h3 id="Credentials">Handling Credentials</h3>
diff --git a/docs/html/training/basics/fragments/support-lib.jd b/docs/html/training/basics/fragments/support-lib.jd
deleted file mode 100644
index a1d781b..0000000
--- a/docs/html/training/basics/fragments/support-lib.jd
+++ /dev/null
@@ -1,83 +0,0 @@
-page.title=Using the Support Library
-page.tags=support library
-helpoutsWidget=true
-
-trainingnavtop=true
-
-@jd:body
-
-<div id="tb-wrapper">
- <div id="tb">
- <h2>This lesson teaches you to</h2>
- <ol>
- <li><a href="#Setup">Set Up Your Project with the Support Library</a></li>
- <li><a href="#Apis">Import the Support Library APIs</a></li>
- </ol>
- <h2>You should also read</h2>
- <ul>
- <li><a href="{@docRoot}tools/support-library/index.html">Support Library</a></li>
- </ul>
- </div>
-</div>
-
-<p>The Android <a href="{@docRoot}tools/support-library/index.html">Support Library</a> provides a JAR
-file with an API library that allows 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
-higher.</p>
-
-<p>This lesson shows how to set up your app to use the Support Library in order to use fragments
-to build a dynamic app UI.</p>
-
-
-<h2 id="Setup">Set Up Your Project with the Support Library</h2>
-
-<div class="figure" style="width:527px">
-<img src="{@docRoot}images/training/basics/sdk-manager.png" alt="" />
-<p class="img-caption"><strong>Figure 1.</strong> The Android SDK Manager with the
-Android Support package selected.</p>
-</div>
-
-<p>To set up your project:</p>
-
-<ol>
- <li>Download the Android Support package using the SDK Manager.</li>
-
- <li>Create a <code>libs</code> directory at the top level of your Android project.</li>
- <li>Locate the JAR file for the library you want to use and copy it into the <code>libs/</code>
-directory.
-<p>For example, the library that supports API level 4 and up is located at
-<code>&lt;sdk>/extras/android/support/v4/android-support-v4.jar</code>.</p></li>
- <li>Update your manifest file to set the minimum API level to <code>4</code> and the target
-API level to the latest release:
- <pre>&lt;uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" /></pre>
- </li>
-</ol>
-
-
-<h2 id="Apis">Import the Support Library APIs</h2>
-
-<p>The Support Library includes a variety of APIs that were either added in recent versions of
-Android or don't exist in the platform at all and merely provide additional support to you when
-developing specific application features.</p>
-
-<p>You can find all the API reference documentation for the Support Library in the
-platform docs at {@link android.support.v4.app android.support.v4.*}.</p>
-
-<div class="warning"><p><strong>Warning:</strong> To be sure that you don't accidentally use new
-APIs on an older system version, be certain that you import the {@link
-android.support.v4.app.Fragment} class and related APIs from the {@link android.support.v4.app}
-package:</p>
-<pre>
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentManager;
-...
-</pre>
-</div>
-
-
-<p>When creating an activity that hosts fragments while using the Support Library, you must also
-extend the {@link android.support.v4.app.FragmentActivity} class instead of the traditional {@link
-android.app.Activity} class. You'll see sample code for the fragment and activity in the next
-lesson.</p>
-
diff --git a/docs/html/training/basics/intents/sending.jd b/docs/html/training/basics/intents/sending.jd
index 4698ba1..b9463e4 100644
--- a/docs/html/training/basics/intents/sending.jd
+++ b/docs/html/training/basics/intents/sending.jd
@@ -153,7 +153,8 @@ java.util.List} is not empty, you can safely use the intent. For example:</p>
<pre>
PackageManager packageManager = {@link android.content.Context#getPackageManager()};
-List&lt;ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
+List<ResolveInfo> activities = packageManager.queryIntentActivities(intent,
+ PackageManager.MATCH_DEFAULT_ONLY);
boolean isIntentSafe = activities.size() > 0;
</pre>
diff --git a/docs/html/training/graphics/opengl/draw.jd b/docs/html/training/graphics/opengl/draw.jd
index ba00627..a588066 100644
--- a/docs/html/training/graphics/opengl/draw.jd
+++ b/docs/html/training/graphics/opengl/draw.jd
@@ -50,13 +50,21 @@ android.opengl.GLSurfaceView.Renderer#onSurfaceCreated onSurfaceCreated()} metho
for memory and processing efficiency.</p>
<pre>
-public void onSurfaceCreated(GL10 unused, EGLConfig config) {
+public class MyGLRenderer implements GLSurfaceView.Renderer {
+
...
+ private Triangle mTriangle;
+ private Square mSquare;
+
+ public void onSurfaceCreated(GL10 unused, EGLConfig config) {
+ ...
- // initialize a triangle
- mTriangle = new Triangle();
- // initialize a square
- mSquare = new Square();
+ // initialize a triangle
+ mTriangle = new Triangle();
+ // initialize a square
+ mSquare = new Square();
+ }
+ ...
}
</pre>
@@ -77,21 +85,27 @@ one or more shapes.</li>
<p>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:</p>
+the shape. Here is an example of how to define basic shaders you can use to draw a shape in the
+<code>Triangle</code> class:</p>
<pre>
-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;" +
- "}";
+public class Triangle {
+
+ 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;" +
+ "}";
+
+ ...
+}
</pre>
<p>Shaders contain OpenGL Shading Language (GLSL) code that must be compiled prior to using it in
@@ -125,13 +139,28 @@ get created once and then cached for later use.</p>
public class Triangle() {
...
- int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
- int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
+ private final int mProgram;
+
+ public Triangle() {
+ ...
+
+ int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
+ vertexShaderCode);
+ int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
+ fragmentShaderCode);
+
+ // create empty OpenGL ES Program
+ mProgram = GLES20.glCreateProgram();
- 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
+ // add the vertex shader to program
+ GLES20.glAttachShader(mProgram, vertexShader);
+
+ // add the fragment shader to program
+ GLES20.glAttachShader(mProgram, fragmentShader);
+
+ // creates OpenGL ES program executables
+ GLES20.glLinkProgram(mProgram);
+ }
}
</pre>
@@ -145,6 +174,12 @@ color values to the shape’s vertex shader and fragment shader, and then execut
function.</p>
<pre>
+private int mPositionHandle;
+private int mColorHandle;
+
+private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
+private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex
+
public void draw() {
// Add program to OpenGL ES environment
GLES20.glUseProgram(mProgram);
@@ -176,8 +211,17 @@ public void draw() {
<p>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:</p>
+android.opengl.GLSurfaceView.Renderer#onDrawFrame onDrawFrame()} method:
+
+<pre>
+public void onDrawFrame(GL10 unused) {
+ ...
+
+ mTriangle.draw();
+}
+</pre>
+
+<p>When you run the application, it should look something like this:</p>
<img src="{@docRoot}images/opengl/ogl-triangle.png">
<p class="img-caption">
diff --git a/docs/html/training/graphics/opengl/environment.jd b/docs/html/training/graphics/opengl/environment.jd
index 6b00c76..cf2b64a 100644
--- a/docs/html/training/graphics/opengl/environment.jd
+++ b/docs/html/training/graphics/opengl/environment.jd
@@ -129,28 +129,22 @@ just create an inner class in the activity that uses it:</p>
<pre>
class MyGLSurfaceView extends GLSurfaceView {
+ private final MyGLRenderer mRenderer;
+
public MyGLSurfaceView(Context context){
super(context);
+ // Create an OpenGL ES 2.0 context
+ setEGLContextClientVersion(2);
+
+ mRenderer = new MyGLRenderer();
+
// Set the Renderer for drawing on the GLSurfaceView
- setRenderer(new MyRenderer());
+ setRenderer(mRenderer);
}
}
</pre>
-<p>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:</p>
-
-<pre>
-// Create an OpenGL ES 2.0 context
-setEGLContextClientVersion(2);
-</pre>
-
-<p class="note"><strong>Note:</strong> If you are using the OpenGL ES 2.0 API, make sure you declare
-this in your application manifest. For more information, see <a href="#manifest">Declare OpenGL ES
-Use
-in the Manifest</a>.</p>
-
<p>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}
@@ -186,7 +180,7 @@ the geometry of the view changes, for example when the device's screen orientati
</ul>
<p>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}:</p>
+black background in the {@link android.opengl.GLSurfaceView}:</p>
<pre>
public class MyGLRenderer implements GLSurfaceView.Renderer {
@@ -208,7 +202,7 @@ public class MyGLRenderer implements GLSurfaceView.Renderer {
</pre>
<p>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
+displays a black 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.</p>
diff --git a/docs/html/training/graphics/opengl/motion.jd b/docs/html/training/graphics/opengl/motion.jd
index fbcdd7f..b026a4a 100644
--- a/docs/html/training/graphics/opengl/motion.jd
+++ b/docs/html/training/graphics/opengl/motion.jd
@@ -45,16 +45,17 @@ to a shape with rotation.</p>
<h2 id="rotate">Rotate a Shape</h2>
-<p>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
+<p>Rotating a drawing object with OpenGL ES 2.0 is relatively simple. In your renderer, create
+another transformation matrix (a rotation matrix) and then combine it with your projection and
camera view transformation matrices:</p>
<pre>
private float[] mRotationMatrix = new float[16];
public void onDrawFrame(GL10 gl) {
- ...
float[] scratch = new float[16];
+ ...
+
// Create a rotation transformation for the triangle
long time = SystemClock.uptimeMillis() % 4000L;
float angle = 0.090f * ((int) time);
diff --git a/docs/html/training/graphics/opengl/projection.jd b/docs/html/training/graphics/opengl/projection.jd
index b09e74c..356d5d4 100644
--- a/docs/html/training/graphics/opengl/projection.jd
+++ b/docs/html/training/graphics/opengl/projection.jd
@@ -71,6 +71,11 @@ projection transformation {@link android.opengl.Matrix} using the {@link
android.opengl.Matrix#frustumM Matrix.frustumM()} method:</p>
<pre>
+// mMVPMatrix is an abbreviation for "Model View Projection Matrix"
+private final float[] mMVPMatrix = new float[16];
+private final float[] mProjectionMatrix = new float[16];
+private final float[] mViewMatrix = new float[16];
+
&#64;Override
public void onSurfaceChanged(GL10 unused, int width, int height) {
GLES20.glViewport(0, 0, width, height);
@@ -95,10 +100,10 @@ view transformation in order for anything to show up on screen.</p>
<h2 id="camera-view">Define a Camera View</h2>
<p>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.</p>
+part of the drawing process in your renderer. 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.</p>
<pre>
&#64;Override
@@ -119,7 +124,32 @@ public void onDrawFrame(GL10 unused) {
<h2 id="#transform">Apply Projection and Camera Transformations</h2>
<p>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
+previews sections, first add a matrix variable to the <em>vertex shader</em> previously defined
+in the <code>Triangle</code> class:</p>
+
+<pre>
+public class Triangle {
+
+ private final String vertexShaderCode =
+ // This matrix member variable provides a hook to manipulate
+ // the coordinates of the objects that use this vertex shader
+ <strong>"uniform mat4 uMVPMatrix;" +</strong>
+ "attribute vec4 vPosition;" +
+ "void main() {" +
+ // the matrix must be included as a modifier of gl_Position
+ // Note that the uMVPMatrix factor *must be first* in order
+ // for the matrix multiplication product to be correct.
+ " gl_Position = <strong>uMVPMatrix</strong> * vPosition;" +
+ "}";
+
+ // Use to access and set the view transformation
+ private int mMVPMatrixHandle;
+
+ ...
+}
+</pre>
+
+<p>Next, modify the {@code draw()} method of your graphic objects to accept the combined
transformation matrix and apply it to the shape:</p>
<pre>
@@ -127,14 +157,16 @@ public void draw(float[] mvpMatrix) { // pass in the calculated transformation m
...
// get handle to shape's transformation matrix
- mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
+ <strong>mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");</strong>
// Pass the projection and view transformation to the shader
- GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
+ <strong>GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);</strong>
// Draw the triangle
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
- ...
+
+ // Disable vertex array
+ GLES20.glDisableVertexAttribArray(mPositionHandle);
}
</pre>
diff --git a/docs/html/training/graphics/opengl/touch.jd b/docs/html/training/graphics/opengl/touch.jd
index 4c9f0c7..089ede7 100644
--- a/docs/html/training/graphics/opengl/touch.jd
+++ b/docs/html/training/graphics/opengl/touch.jd
@@ -50,6 +50,10 @@ android.opengl.GLSurfaceView#onTouchEvent onTouchEvent()} to listen for touch ev
an angle of rotation for a shape.</p>
<pre>
+private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
+private float mPreviousX;
+private float mPreviousY;
+
&#64;Override
public boolean onTouchEvent(MotionEvent e) {
// MotionEvent reports input details from the touch screen
@@ -77,7 +81,7 @@ public boolean onTouchEvent(MotionEvent e) {
mRenderer.setAngle(
mRenderer.getAngle() +
- ((dx + dy) * TOUCH_SCALE_FACTOR); // = 180.0f / 320
+ ((dx + dy) * TOUCH_SCALE_FACTOR));
requestRender();
}
@@ -108,12 +112,22 @@ public MyGLSurfaceView(Context context) {
<p>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:</p>
+Here is the code to declare the variable and expose the getter and setter pair:</p>
<pre>
public class MyGLRenderer implements GLSurfaceView.Renderer {
...
+
public volatile float mAngle;
+
+ public float getAngle() {
+ return mAngle;
+ }
+
+ public void setAngle(float angle) {
+ mAngle = angle;
+ }
+}
</pre>
diff --git a/docs/html/training/location/display-address.jd b/docs/html/training/location/display-address.jd
index 621b082..516f14f 100644
--- a/docs/html/training/location/display-address.jd
+++ b/docs/html/training/location/display-address.jd
@@ -1,280 +1,468 @@
page.title=Displaying a Location Address
-
trainingnavtop=true
-
@jd:body
-
-
<div id="tb-wrapper">
-<div id="tb">
+ <div id="tb">
-<h2>This lesson teaches you to</h2>
-<ol>
- <li><a href="#DefineTask">Define the Address Lookup Task</a></li>
- <li><a href="#DisplayResults">Define a Method to Display the Results</a></li>
- <li><a href="#RunTask">Run the Lookup Task</a></li>
-</ol>
+ <h2>This lesson teaches you how to</h2>
+ <ol>
+ <li><a href="#connect">Get a Geographic Location</a></li>
+ <li><a href="#fetch-address">Define an Intent Service to Fetch the
+ Address</a></li>
+ <li><a href="#start-intent">Start the Intent Service</a></li>
+ <li><a href="#result-receiver">Receive the Geocoding Results</a></li>
+ </ol>
-<h2>You should also read</h2>
-<ul>
- <li>
- <a href="{@docRoot}google/play-services/setup.html">Setup Google Play Services SDK</a>
- </li>
- <li>
- <a href="retrieve-current.html">Retrieving the Current Location</a>
- </li>
- <li>
- <a href="receive-location-updates.html">Receiving Location Updates</a>
- </li>
-</ul>
-<h2>Try it out</h2>
+ <h2>You should also read</h2>
+ <ul>
+ <li>
+ <a href="{@docRoot}google/play-services/setup.html">Setting up Google
+ Play Services</a>
+ </li>
+ <li>
+ <a href="retrieve-current.html">Getting the Last Known Location</a>
+ </li>
+ <li>
+ <a href="receive-location-updates.html">Receiving Location Updates</a>
+ </li>
+ </ul>
+ <h2>Try it out</h2>
-<div class="download-box">
-<a href="http://developer.android.com/shareables/training/LocationUpdates.zip" class="button">Download
- the sample app</a>
-<p class="filename">LocationUpdates.zip</p>
+ <ul>
+ <li>
+ <a href="https://github.com/googlesamples/android-play-location/tree/master/LocationAddress" class="external-link">LocationAddress</a>
+ </li>
+ </ul>
+ </div>
</div>
-</div>
-</div>
+<p>The lessons <a href="retrieve-current.html">Getting the Last Known
+ Location</a> and <a href="receive-location-updates.html">Receiving Location
+ Updates</a> describe how to get the user's location in the form of a
+ {@link android.location.Location} object that contains latitude and longitude
+ coordinates. Although latitude and longitude are useful for calculating
+ distance or displaying a map position, in many cases the address of the
+ location is more useful. For example, if you want to let your users know where
+ they are or what is close by, a street address is more meaningful than the
+ geographic coordinates (latitude/longitude) of the location.</p>
+
+<p>Using the {@link android.location.Geocoder} class in the Android framework
+ location APIs, you can convert an address to the corresponding geographic
+ coordinates. This process is called <em>geocoding</em>. Alternatively, you can
+ convert a geographic location to an address. The address lookup feature is
+ also known as <em>reverse geocoding</em>.</p>
+
+<p>This lesson shows you how to use the
+ {@link android.location.Geocoder#getFromLocation getFromLocation()} method to
+ convert a geographic location to an address. The method returns an estimated
+ street address corresponding to a given latitude and longitude.</p>
+
+<h2 id="connect">Get a Geographic Location</h2>
+
+<p>The last known location of the device is a useful starting point for the
+ address lookup feature. The lesson on
+ <a href="retrieve-current.html">Getting the Last Known Location</a> shows you
+ how to use the
+ <a href="{@docRoot}reference/com/google/android/gms/location/FusedLocationProviderApi.html#getLastLocation(com.google.android.gms.common.api.GoogleApiClient)">{@code getLastLocation()}</a>
+ method provided by the
+ <a href="{@docRoot}reference/com/google/android/gms/location/FusedLocationProviderApi.html">fused
+ location provider</a> to find the latest location of the device.</p>
+
+<p>To access the fused location provider, you need to create an instance of the
+ Google Play services API client. To learn how to connect your client, see
+ <a href="{@docRoot}training/location/retrieve-current.html#play-services">Connect
+ to Google Play Services</a>.</p>
+
+<p>In order for the fused location provider to retrieve a precise street
+ address, set the location permission in your app manifest to
+ {@code ACCESS_FINE_LOCATION}, as shown in the following example:</p>
-<p>
- The lessons <a href="retrieve-current.html">Retrieving the Current Location</a> and
- <a href="receive-location-updates.html">Receiving Location Updates</a> describe how to get the
- user's current location in the form of a {@link android.location.Location} object that
- contains latitude and longitude coordinates. Although latitude and longitude are useful for
- calculating distance or displaying a map position, in many cases the address of the location is
- more useful.
-</p>
-<p>
- The Android platform API provides a feature that returns an estimated street addresses for
- latitude and longitude values. This lesson shows you how to use this address lookup feature.
-</p>
-<p class="note">
- <strong>Note:</strong> Address lookup requires a backend service that is not included in the
- core Android framework. If this backend service is not available,
- {@link android.location.Geocoder#getFromLocation Geocoder.getFromLocation()} returns an empty
- list. The helper method {@link android.location.Geocoder#isPresent isPresent()}, available
- in API level 9 and later, checks to see if the backend service is available.
-</p>
-<p>
- The snippets in the following sections assume that your app has already retrieved the
- current location and stored it as a {@link android.location.Location} object in the global
- variable {@code mLocation}.
-</p>
-<!--
- Define the address lookup task
--->
-<h2 id="DefineTask">Define the Address Lookup Task</h2>
-<p>
-To get an address for a given latitude and longitude, call
-{@link android.location.Geocoder#getFromLocation Geocoder.getFromLocation()}, which returns a
-list of addresses. The method is synchronous, and may take a long time to do its work, so you
-should call the method from the {@link android.os.AsyncTask#doInBackground
-doInBackground()} method of an {@link android.os.AsyncTask}.
-</p>
-<p>
-While your app is getting the address, display an indeterminate activity
-indicator to show that your app is working in the background. Set the indicator's initial state
-to {@code android:visibility="gone"}, to make it invisible and remove it from the layout
-hierarchy. When you start the address lookup, you set its visibility to "visible".
-</p>
-<p>
-The following snippet shows how to add an indeterminate {@link android.widget.ProgressBar} to
-your layout file:
-</p>
<pre>
-&lt;ProgressBar
-android:id="&#64;+id/address_progress"
-android:layout_width="wrap_content"
-android:layout_height="wrap_content"
-android:layout_centerHorizontal="true"
-android:indeterminate="true"
-android:visibility="gone" /&gt;
+&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.google.android.gms.location.sample.locationupdates" &gt;
+
+ &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt;
+&lt;/manifest&gt;
</pre>
-<p>
-To create the background task, define a subclass of {@link android.os.AsyncTask} that calls
-{@link android.location.Geocoder#getFromLocation getFromLocation()} and returns an address.
-Define a {@link android.widget.TextView} object {@code mAddress} to contain the returned
-address, and a {@link android.widget.ProgressBar} object that allows you to control the
-indeterminate activity indicator. For example:
-</p>
+
+<h2 id="fetch-address">Define an Intent Service to Fetch the Address</h2>
+
+<p>The {@link android.location.Geocoder#getFromLocation getFromLocation()}
+ method provided by the {@link android.location.Geocoder} class accepts a
+ latitude and longitude, and returns a list of addresses. The method is
+ synchronous, and may take a long time to do its work, so you should not call
+ it from the main, user interface (UI) thread of your app.</p>
+
+<p>The {@link android.app.IntentService IntentService} class provides a
+ structure for running a task on a background thread. Using this class, you can
+ handle a long-running operation without affecting your UI's responsiveness.
+ Note that the {@link android.os.AsyncTask AsyncTask} class also allows you to
+ perform background operations, but it's designed for short operations. An
+ {@link android.os.AsyncTask AsyncTask} shouldn't keep a reference to the UI if
+ the activity is recreated, for example when the device is rotated. In
+ contrast, an {@link android.app.IntentService IntentService} doesn't need to
+ be cancelled when the activity is rebuilt.</p>
+
+<p>Define a {@code FetchAddressIntentService} class that extends
+ {@link android.app.IntentService}. This class is your address lookup service.
+ The intent service handles an intent asynchronously on a worker thread, and
+ stops itself when it runs out of work. The intent extras provide the data
+ needed by the service, including a {@link android.location.Location} object
+ for conversion to an address, and a {@link android.os.ResultReceiver} object
+ to handle the results of the address lookup. The service uses a {@link
+ android.location.Geocoder} to fetch the address for the location, and sends
+ the results to the {@link android.os.ResultReceiver}.</p>
+
+<h3>Define the Intent Service in your App Manifest</h3>
+
+<p>Add an entry to your app manifest defining the intent service:</p>
+
<pre>
-public class MainActivity extends FragmentActivity {
+&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.google.android.gms.location.sample.locationaddress" &gt;
+ &lt;application
+ ...
+ &lt;service
+ android:name=".FetchAddressIntentService"
+ android:exported="false"/&gt;
+ &lt;/application&gt;
...
- private TextView mAddress;
- private ProgressBar mActivityIndicator;
+&lt;/manifest&gt;
+</pre>
+
+<p class="note"><strong>Note:</strong> The {@code &lt;service&gt;} element in
+ the manifest doesn't need to include an intent filter, because your main
+ activity creates an explicit intent by specifying the name of the class to use
+ for the intent.</p>
+
+<h3>Create a Geocoder</h3>
+
+<p>The process of converting a geographic location to an address is called
+ <em>reverse geocoding</em>. To perform the main work of the intent service,
+ that is, your reverse geocoding request, implement
+ {@link android.app.IntentService#onHandleIntent onHandleIntent()} within the
+ {@code FetchAddressIntentService} class. Create a
+ {@link android.location.Geocoder} object to handle the reverse geocoding.</p>
+
+<p>A locale represents a specific geographical or linguistic region. Locale
+ objects are used to adjust the presentation of information, such as numbers or
+ dates, to suit the conventions in the region represented by the locale. Pass a
+ <a href="{@docRoot}reference/java/util/Locale.html">{@code Locale}</a> object
+ to the {@link android.location.Geocoder} object, to ensure that the resulting
+ address is localized to the user's geographic region.</p>
+
+<pre>
+&#64;Override
+protected void onHandleIntent(Intent intent) {
+ Geocoder geocoder = new Geocoder(this, Locale.getDefault());
...
- &#64;Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
+}
+</pre>
+
+<h3 id="retrieve-street-address">Retrieve the street address data</h3>
+
+<p>The next step is to retrieve the street address from the geocoder, handle
+ any errors that may occur, and send the results back to the activity that
+ requested the address. To report the results of the geocoding
+ process, you need two numeric constants that indicate success or failure.
+ Define a {@code Constants} class to contain the values, as shown in this code
+ snippet:</p>
+
+<pre>
+public final class Constants {
+ public static final int SUCCESS_RESULT = 0;
+ public static final int FAILURE_RESULT = 1;
+ public static final String PACKAGE_NAME =
+ "com.google.android.gms.location.sample.locationaddress";
+ public static final String RECEIVER = PACKAGE_NAME + ".RECEIVER";
+ public static final String RESULT_DATA_KEY = PACKAGE_NAME +
+ ".RESULT_DATA_KEY";
+ public static final String LOCATION_DATA_EXTRA = PACKAGE_NAME +
+ ".LOCATION_DATA_EXTRA";
+}
+</pre>
+
+<p>To get a street address corresponding to a geographical location, call
+ {@link android.location.Geocoder#getFromLocation getFromLocation()},
+ passing it the latitude and longitude from the location object, and the
+ maximum number of addresses you want returned. In this case, you want just one
+ address. The geocoder returns an array of addresses. If no addresses were
+ found to match the given location, it returns an empty list. If there is no
+ backend geocoding service available, the geocoder returns null.</p>
+
+<p>Check for the following errors as shown in the code sample below. If an error
+ occurs, place the corresponding error message in the {@code errorMessage}
+ variable, so you can send it back to the requesting activity:</p>
+
+<ul>
+ <li><strong>No location data provided</strong> - The intent extras do not
+ include the {@link android.location.Location} object required for reverse
+ geocoding.</li>
+ <li><strong>Invalid latitude or longitude used</strong> - The latitude
+ and/or longitude values provided in the {@link android.location.Location}
+ object are invalid.</li>
+ <li><strong>No geocoder available</strong> - The background geocoding service
+ is not available, due to a network error or IO exception.</li>
+ <li><strong>Sorry, no address found</strong> - The geocoder could not find an
+ address for the given latitude/longitude.</li>
+</ul>
+
+<p>To get the individual lines of an address object, use the
+ {@link android.location.Address#getAddressLine getAddressLine()}
+ method provided by the {@link android.location.Address} class. Then join the
+ lines into a list of address fragments ready to return to the activity that
+ requested the address.</p>
+
+<p>To send the results back to the requesting activity, call the
+ {@code deliverResultToReceiver()} method (defined in
+ <a href="#return-address">Return the address to the requestor</a>). The
+ results consist of the previously-mentioned numeric success/failure code and
+ a string. In the case of a successful reverse geocoding, the string contains
+ the address. In the case of a failure, the string contains the error message,
+ as shown in the code sample below:</p>
+
+<pre>
+&#64;Override
+protected void onHandleIntent(Intent intent) {
+ String errorMessage = "";
+
+ // Get the location passed to this service through an extra.
+ Location location = intent.getParcelableExtra(
+ Constants.LOCATION_DATA_EXTRA);
+
...
- mAddress = (TextView) findViewById(R.id.address);
- mActivityIndicator =
- (ProgressBar) findViewById(R.id.address_progress);
+
+ List&lt;Address&gt; addresses = null;
+
+ try {
+ addresses = geocoder.getFromLocation(
+ location.getLatitude(),
+ location.getLongitude(),
+ // In this sample, get just a single address.
+ 1);
+ } catch (IOException ioException) {
+ // Catch network or other I/O problems.
+ errorMessage = getString(R.string.service_not_available);
+ Log.e(TAG, errorMessage, ioException);
+ } catch (IllegalArgumentException illegalArgumentException) {
+ // Catch invalid latitude or longitude values.
+ errorMessage = getString(R.string.invalid_lat_long_used);
+ Log.e(TAG, errorMessage + ". " +
+ "Latitude = " + location.getLatitude() +
+ ", Longitude = " +
+ location.getLongitude(), illegalArgumentException);
}
- ...
- /**
- * A subclass of AsyncTask that calls getFromLocation() in the
- * background. The class definition has these generic types:
- * Location - A {@link android.location.Location} object containing
- * the current location.
- * Void - indicates that progress units are not used
- * String - An address passed to onPostExecute()
- */
- private class GetAddressTask extends
- AsyncTask&lt;Location, Void, String&gt; {
- Context mContext;
- public GetAddressTask(Context context) {
- super();
- mContext = context;
+
+ // Handle case where no address was found.
+ if (addresses == null || addresses.size() == 0) {
+ if (errorMessage.isEmpty()) {
+ errorMessage = getString(R.string.no_address_found);
+ Log.e(TAG, errorMessage);
}
- ...
- /**
- * Get a Geocoder instance, get the latitude and longitude
- * look up the address, and return it
- *
- * &#64;params params One or more Location objects
- * &#64;return A string containing the address of the current
- * location, or an empty string if no address can be found,
- * or an error message
- */
- &#64;Override
- protected String doInBackground(Location... params) {
- Geocoder geocoder =
- new Geocoder(mContext, Locale.getDefault());
- // Get the current location from the input parameter list
- Location loc = params[0];
- // Create a list to contain the result address
- List&lt;Address&gt; addresses = null;
- try {
- /*
- * Return 1 address.
- */
- addresses = geocoder.getFromLocation(loc.getLatitude(),
- loc.getLongitude(), 1);
- } catch (IOException e1) {
- Log.e("LocationSampleActivity",
- "IO Exception in getFromLocation()");
- e1.printStackTrace();
- return ("IO Exception trying to get address");
- } catch (IllegalArgumentException e2) {
- // Error message to post in the log
- String errorString = "Illegal arguments " +
- Double.toString(loc.getLatitude()) +
- " , " +
- Double.toString(loc.getLongitude()) +
- " passed to address service";
- Log.e("LocationSampleActivity", errorString);
- e2.printStackTrace();
- return errorString;
- }
- // If the reverse geocode returned an address
- if (addresses != null &amp;&amp; addresses.size() &gt; 0) {
- // Get the first address
- Address address = addresses.get(0);
- /*
- * Format the first line of address (if available),
- * city, and country name.
- */
- String addressText = String.format(
- "&#037;s, &#037;s, &#037;s",
- // If there's a street address, add it
- address.getMaxAddressLineIndex() &gt; 0 ?
- address.getAddressLine(0) : "",
- // Locality is usually a city
- address.getLocality(),
- // The country of the address
- address.getCountryName());
- // Return the text
- return addressText;
- } else {
- return "No address found";
- }
+ deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
+ } else {
+ Address address = addresses.get(0);
+ ArrayList&lt;String&gt; addressFragments = new ArrayList&lt;String&gt;();
+
+ // Fetch the address lines using {@code getAddressLine},
+ // join them, and send them to the thread.
+ for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
+ addressFragments.add(address.getAddressLine(i));
}
- ...
+ Log.i(TAG, getString(R.string.address_found));
+ deliverResultToReceiver(Constants.SUCCESS_RESULT,
+ TextUtils.join(System.getProperty("line.separator"),
+ addressFragments));
}
- ...
}
</pre>
-<p>
-The next section shows you how to display the address in the user interface.
-</p>
-<!-- Define a method to display the address -->
-<h2 id="DisplayResults">Define a Method to Display the Results</h2>
-<p>
- {@link android.os.AsyncTask#doInBackground doInBackground()} returns the result of the address
- lookup as a {@link java.lang.String}. This value is passed to
- {@link android.os.AsyncTask#onPostExecute onPostExecute()}, where you do further processing
- on the results. Since {@link android.os.AsyncTask#onPostExecute onPostExecute()}
- runs on the UI thread, it can update the user interface; for example, it can turn off the
- activity indicator and display the results to the user:
+
+<h3 id="return-address">Return the address to the requestor</h3>
+
+<p>The final thing the intent service must do is send the address back to a
+ {@link android.os.ResultReceiver} in the activity that started the service.
+ The {@link android.os.ResultReceiver} class allows you to send a
+ numeric result code as well as a message containing the result data. The
+ numeric code is useful for reporting the success or failure of the geocoding
+ request. In the case of a successful reverse geocoding, the message contains
+ the address. In the case of a failure, the message contains some text
+ describing the reason for failure.</p>
+
+<p>You have already retrieved the address from the geocoder, trapped any errors
+ that may occur, and called the {@code deliverResultToReceiver()} method. Now
+ you need to define the {@code deliverResultToReceiver()} method that sends
+ a result code and message bundle to the result receiver.</p>
+
+<p>For the result code, use the value that you've passed to the
+ {@code deliverResultToReceiver()} method in the {@code resultCode} parameter.
+ To construct the message bundle, concatenate the {@code RESULT_DATA_KEY}
+ constant from your {@code Constants} class (defined in
+ <a href="#retrieve-street-address">Retrieve the street address data</a>) and
+ the value in the {@code message} parameter passed to the
+ {@code deliverResultToReceiver()} method, as shown in the following sample:
</p>
+
<pre>
- private class GetAddressTask extends
- AsyncTask&lt;Location, Void, String&gt; {
- ...
- /**
- * A method that's called once doInBackground() completes. Turn
- * off the indeterminate activity indicator and set
- * the text of the UI element that shows the address. If the
- * lookup failed, display the error message.
- */
- &#64;Override
- protected void onPostExecute(String address) {
- // Set activity indicator visibility to "gone"
- mActivityIndicator.setVisibility(View.GONE);
- // Display the results of the lookup.
- mAddress.setText(address);
- }
- ...
+public class FetchAddressIntentService extends IntentService {
+ protected ResultReceiver mReceiver;
+ ...
+ private void deliverResultToReceiver(int resultCode, String message) {
+ Bundle bundle = new Bundle();
+ bundle.putString(Constants.RESULT_DATA_KEY, message);
+ mReceiver.send(resultCode, bundle);
}
+}
</pre>
-<p>
- The final step is to run the address lookup.
-</p>
-<!-- Get and display the address -->
-<h2 id="RunTask">Run the Lookup Task</h2>
-<p>
- To get the address, call {@link android.os.AsyncTask#execute execute()}. For example, the
- following snippet starts the address lookup when the user clicks the "Get Address" button:
-</p>
+
+<h2 id="start-intent">Start the Intent Service</h2>
+
+<p>The intent service, as defined in the previous section, runs in the
+ background and is responsible for fetching the address corresponding to a
+ given geographic location. When you start the service, the Android framework
+ instantiates and starts the service if it isn't already running, and creates a
+ process if needed. If the service is already running then it remains running.
+ Because the service extends {@link android.app.IntentService IntentService},
+ it shuts down automatically when all intents have been processed.</p>
+
+<p>Start the service from your app's main activity,
+ and create an {@link android.content.Intent} to pass data to the service. You
+ need an <em>explicit</em> intent, because you want only your service
+ to respond to the intent. For more information, see
+ <a href="{@docRoot}guide/components/intents-filters.html#Types">Intent
+ Types</a>.</p>
+
+<p>To create an explicit intent, specify the name of the
+ class to use for the service: {@code FetchAddressIntentService.class}.
+ Pass two pieces of information in the intent extras:</p>
+
+<ul>
+ <li>A {@link android.os.ResultReceiver} to handle the results of the address
+ lookup.</li>
+ <li>A {@link android.location.Location} object containing the latitude and
+ longitude that you want to convert to an address.</li>
+</ul>
+
+<p>The following code sample shows you how to start the intent service:</p>
+
<pre>
-public class MainActivity extends FragmentActivity {
+public class MainActivity extends ActionBarActivity implements
+ ConnectionCallbacks, OnConnectionFailedListener {
+
+ protected Location mLastLocation;
+ private AddressResultReceiver mResultReceiver;
...
- /**
- * The "Get Address" button in the UI is defined with
- * android:onClick="getAddress". The method is invoked whenever the
- * user clicks the button.
- *
- * &#64;param v The view object associated with this method,
- * in this case a Button.
- */
- public void getAddress(View v) {
- // Ensure that a Geocoder services is available
- if (Build.VERSION.SDK_INT &gt;=
- Build.VERSION_CODES.GINGERBREAD
- &amp;&amp;
- Geocoder.isPresent()) {
- // Show the activity indicator
- mActivityIndicator.setVisibility(View.VISIBLE);
- /*
- * Reverse geocoding is long-running and synchronous.
- * Run it on a background thread.
- * Pass the current location to the background task.
- * When the task finishes,
- * onPostExecute() displays the address.
- */
- (new GetAddressTask(this)).execute(mLocation);
+
+ protected void startIntentService() {
+ Intent intent = new Intent(this, FetchAddressIntentService.class);
+ intent.putExtra(Constants.RECEIVER, mResultReceiver);
+ intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation);
+ startService(intent);
+ }
+}
+</pre>
+
+<p>Call the above {@code startIntentService()} method when the
+ user takes an action that requires a geocoding address lookup. For example,
+ the user may press a <em>Fetch address</em> button on your app's UI. Before
+ starting the intent service, you need to check that the connection to Google
+ Play services is present. The following code snippet shows the call to the
+ {@code startIntentService()} method in the button handler:</p>
+
+<pre>
+public void fetchAddressButtonHandler(View view) {
+ // Only start the service to fetch the address if GoogleApiClient is
+ // connected.
+ if (mGoogleApiClient.isConnected() && mLastLocation != null) {
+ startIntentService();
+ }
+ // If GoogleApiClient isn't connected, process the user's request by
+ // setting mAddressRequested to true. Later, when GoogleApiClient connects,
+ // launch the service to fetch the address. As far as the user is
+ // concerned, pressing the Fetch Address button
+ // immediately kicks off the process of getting the address.
+ mAddressRequested = true;
+ updateUIWidgets();
+}
+</pre>
+
+<p>You must also start the intent service when the connection to Google Play
+ services is established, if the user has already clicked the button on your
+ app's UI. The following code snippet shows the call to the
+ {@code startIntentService()} method in the
+ <a href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.ConnectionCallbacks.html#onConnected(android.os.Bundle)">{@code onConnected()}</a>
+ callback provided by the Google API Client:</p>
+
+<pre>
+public class MainActivity extends ActionBarActivity implements
+ ConnectionCallbacks, OnConnectionFailedListener {
+ ...
+ &#64;Override
+ public void onConnected(Bundle connectionHint) {
+ // Gets the best and most recent location currently available,
+ // which may be null in rare cases when a location is not available.
+ mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
+ mGoogleApiClient);
+
+ if (mLastLocation != null) {
+ // Determine whether a Geocoder is available.
+ if (!Geocoder.isPresent()) {
+ Toast.makeText(this, R.string.no_geocoder_available,
+ Toast.LENGTH_LONG).show();
+ return;
+ }
+
+ if (mAddressRequested) {
+ startIntentService();
+ }
}
- ...
}
+}
+</pre>
+
+<h2 id="result-receiver">Receive the Geocoding Results</h2>
+
+<p>The intent service has handled the geocoding request, and uses a
+ {@link android.os.ResultReceiver} to return the results to the activity that
+ made the request. In the activity that makes the request, define an
+ {@code AddressResultReceiver} that extends {@link android.os.ResultReceiver}
+ to handle the response from {@code FetchAddressIntentService}.</p>
+
+<p>The result includes a numeric result code (<code>resultCode</code>) as well
+ as a message containing the result data (<code>resultData</code>). If the
+ reverse geocoding process was successful, the <code>resultData</code> contains
+ the address. In the case of a failure, the <code>resultData</code> contains
+ text describing the reason for failure. For details of the possible errors,
+ see <a href="#return-address">Return the address to the requestor</a>.</p>
+
+<p>Override the
+ {@link android.os.ResultReceiver#onReceiveResult onReceiveResult()} method
+ to handle the results delivered to the result receiver, as shown in the
+ following code sample:</p>
+
+<pre>
+public class MainActivity extends ActionBarActivity implements
+ ConnectionCallbacks, OnConnectionFailedListener {
...
+ class AddressResultReceiver extends ResultReceiver {
+ public AddressResultReceiver(Handler handler) {
+ super(handler);
+ }
+
+ &#64;Override
+ protected void onReceiveResult(int resultCode, Bundle resultData) {
+
+ // Display the address string
+ // or an error message sent from the intent service.
+ mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
+ displayAddressOutput();
+
+ // Show a toast message if an address was found.
+ if (resultCode == Constants.SUCCESS_RESULT) {
+ showToast(getString(R.string.address_found));
+ }
+
+ }
+ }
}
</pre>
-<p>
- The next lesson, <a href="geofencing.html">Creating and Monitoring Geofences</a>, demonstrates
- how to define locations of interest called <b>geofences</b> and how to use geofence monitoring
- to detect the user's proximity to a location of interest.
-</p>
diff --git a/docs/html/training/material/drawables.jd b/docs/html/training/material/drawables.jd
index 820a004..a2de8e9 100644
--- a/docs/html/training/material/drawables.jd
+++ b/docs/html/training/material/drawables.jd
@@ -73,7 +73,7 @@ app's module:</p>
<pre>
dependencies {
...
- compile 'com.android.support:palette-v7:21.0.+'
+ compile 'com.android.support:palette-v7:21.0.0'
}
</pre>
diff --git a/docs/html/training/multiscreen/screendensities.jd b/docs/html/training/multiscreen/screendensities.jd
index fcb65cc..1fc5904 100644
--- a/docs/html/training/multiscreen/screendensities.jd
+++ b/docs/html/training/multiscreen/screendensities.jd
@@ -28,6 +28,7 @@ next.link=adaptui.html
<ul>
<li><a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple Screens</a></li>
+ <li><a href="{@docRoot}design/style/iconography.html">Iconography</a></li>
<li><a href="{@docRoot}guide/practices/ui_guidelines/icon_design.html">Icon Design
Guidelines</a></li>
</ul>
@@ -133,6 +134,28 @@ MyProject/
<p>Then, any time you reference <code>&#64;drawable/awesomeimage</code>, the system selects the
appropriate bitmap based on the screen's dpi.</p>
+<p>Place your launcher icons in the <code>mipmap/</code> folders. </p>
+
+<pre>res/...
+ mipmap-ldpi/...
+ <em>finished_launcher_asset</em>.png
+ mipmap-mdpi/...
+ <em>finished_launcher_asset</em>.png
+ mipmap-hdpi/...
+ <em>finished_launcher_asset</em>.png
+ mipmap-xhdpi/...
+ <em>finished_launcher_asset</em>.png
+ mipmap-xxhdpi/...
+ <em>finished_launcher_asset</em>.png
+ mipmap-xxxhdpi/...
+ <em>finished_launcher_asset</em>.png
+</pre>
+
+<p class="note"><strong>Note:</strong> You should place all launcher icons in the
+<code>res/mipmap-[density]/</code> folders, rather than <code>drawable/</code> folders to ensure
+launcher apps use the best resolution icon. For more information about using the mipmap folders, see
+<a href="{@docRoot}tools/project/index.html#mipmap">Managing Projects Overview</a>.</p>
+
<p>For more tips and guidelines for creating icon assets for your application, see the <a
href="{@docRoot}guide/practices/ui_guidelines/icon_design.html">Icon Design
Guidelines</a>.</p>
diff --git a/docs/html/training/training_toc.cs b/docs/html/training/training_toc.cs
index 0fcfb9c..c59d8ff 100644
--- a/docs/html/training/training_toc.cs
+++ b/docs/html/training/training_toc.cs
@@ -437,6 +437,35 @@ include the action bar on devices running Android 2.1 or higher."
</li>
</ul>
</li>
+
+ <li class="nav-section">
+ <div class="nav-section-header">
+ <a href="<?cs var:toroot?>training/transitions/index.html"
+ description=
+ "How to animate state changes in a view hierarchy using transitions."
+ >Animating Views Using Scenes and Transitions</a>
+ </div>
+ <ul>
+ <li><a href="<?cs var:toroot ?>training/transitions/overview.html">
+ The Transitions Framework
+ </a>
+ </li>
+ <li><a href="<?cs var:toroot ?>training/transitions/scenes.html">
+ Creating a Scene
+ </a>
+ </li>
+ <li><a href="<?cs var:toroot ?>training/transitions/transitions.html">
+ Applying a Transition
+ </a>
+ </li>
+ <li><a href="<?cs var:toroot ?>training/transitions/custom-transitions.html">
+ Creating Custom Transitions
+ </a>
+ </li>
+
+ </ul>
+ </li>
+
<li class="nav-section">
<div class="nav-section-header"><a href="<?cs var:toroot ?>training/animation/index.html"
description=
@@ -922,6 +951,10 @@ include the action bar on devices running Android 2.1 or higher."
Creating a Catalog Browser</a>
</li>
<li>
+ <a href="<?cs var:toroot ?>training/tv/playback/card.html">
+ Providing a Card View</a>
+ </li>
+ <li>
<a href="<?cs var:toroot ?>training/tv/playback/details.html"
ja-lang="詳細ビューをビルドする">
Building a Details View</a>
@@ -1854,4 +1887,4 @@ results."
buildToggleLists();
changeNavLang(getLangPref());
//-->
-</script>
+</script> \ No newline at end of file
diff --git a/docs/html/training/transitions/custom-transitions.jd b/docs/html/training/transitions/custom-transitions.jd
new file mode 100644
index 0000000..b64daae
--- /dev/null
+++ b/docs/html/training/transitions/custom-transitions.jd
@@ -0,0 +1,189 @@
+page.title=Creating Custom Transitions
+
+@jd:body
+
+<div id="tb-wrapper">
+<div id="tb">
+<h2>This lesson teaches you to</h2>
+<ol>
+ <li><a href="#Extend">Extend the Transition Class</a></li>
+ <li><a href="#CaptureProperties">Capture View Property Values</a></li>
+ <li><a href="#CreateAnimator">Create a Custom Animator</a></li>
+ <li><a href="#Apply">Apply a Custom Transition</a></li>
+</ol>
+</div>
+</div>
+
+<p>A custom transition enables you to create an animation that is not available from any of
+the built-in transition classes. For example, you can define a custom transition that turns
+the foreground color of text and input fields to gray to indicate that the fields are disabled
+in the new screen. This type of change helps users see the fields you disabled.</p>
+
+<p>A custom transition, like one of the built-in transition types, applies animations to
+child views of both the starting and ending scenes. Unlike built-in transition types,
+however, you have to provide the code that captures property values and generates animations.
+You may also want to define a subset of target views for your animation.</p>
+
+<p>This lesson teaches you to capture property values and generate animations to create
+custom transitions.</p>
+
+
+
+<h2 id="Extend">Extend the Transition Class</h2>
+
+<p>To create a custom transition, add a class to your project that extends the {@link
+android.transition.Transition} class and override the methods shown in the following snippet:</p>
+
+<pre>
+public class CustomTransition extends Transition {
+
+ &#64;Override
+ public void captureStartValues(TransitionValues values) {}
+
+ &#64;Override
+ public void captureEndValues(TransitionValues values) {}
+
+ &#64;Override
+ public Animator createAnimator(ViewGroup sceneRoot,
+ TransitionValues startValues,
+ TransitionValues endValues) {}
+}
+</pre>
+
+<p>The following sections explain how to override these methods.</p>
+
+
+
+<h2 id="CaptureProperties">Capture View Property Values</h2>
+
+<p>Transition animations use the property animation system described in
+<a href="{@docRoot}guide/topics/graphics/prop-animation.html">Property Animation</a>. Property
+animations change a view property between a starting and ending value over a specified
+period of time, so the framework needs to have both the starting and ending value of
+the property to construct the animation.</p>
+
+<p>However, a property animation usually needs only a small subset of all the view's property
+values. For example, a color animation needs color property values, while a movement
+animation needs position property values. Since the property values needed for an animation
+are specific to a transition, the transitions framework does not provide every property value
+to a transition. Instead, the framework invokes callback methods that allow a transition to
+capture only the property values it needs and store them in the framework.</p>
+
+
+<h3 id="StartingValues">Capturing Starting Values</h3>
+
+<p>To pass the starting view values to the framework, implement the
+{@link android.transition.Transition#captureStartValues captureStartValues(transitionValues)}
+method. The framework calls this method for every view in the starting scene. The method
+argument is a {@link android.transition.TransitionValues} object that contains a reference
+to the view and a {@link java.util.Map} instance in which you can store the view values you
+want. In your implementation, retrieve these property values and pass them back to the
+framework by storing them in the map.</p>
+
+<p>To ensure that the key for a property value does not conflict with other {@link
+android.transition.TransitionValues} keys, use the following naming scheme:</p>
+
+<pre>
+package_name:transition_name:property_name
+</pre>
+
+<p>The following snippet shows an implementation of the {@link
+android.transition.Transition#captureStartValues captureStartValues()} method:</p>
+
+<pre>
+public class CustomTransition extends Transition {
+
+ // Define a key for storing a property value in
+ // TransitionValues.values with the syntax
+ // package_name:transition_class:property_name to avoid collisions
+ private static final String PROPNAME_BACKGROUND =
+ "com.example.android.customtransition:CustomTransition:background";
+
+ &#64;Override
+ public void captureStartValues(TransitionValues transitionValues) {
+ // Call the convenience method captureValues
+ captureValues(transitionValues);
+ }
+
+
+ // For the view in transitionValues.view, get the values you
+ // want and put them in transitionValues.values
+ private void captureValues(TransitionValues transitionValues) {
+ // Get a reference to the view
+ View view = transitionValues.view;
+ // Store its background property in the values map
+ transitionValues.values.put(PROPNAME_BACKGROUND, view.getBackground());
+ }
+ ...
+}
+</pre>
+
+
+<h3 id="EndingValues">Capture Ending Values</h3>
+
+<p>The framework calls the {@link android.transition.Transition#captureEndValues} method
+once for every target view in the ending scene. In all other respects, {@link
+android.transition.Transition#captureEndValues captureEndValues()} works the same as {@link
+android.transition.Transition#captureStartValues captureStartValues()}.</p>
+
+<p>The following code snippet shows an implementation of the {@link
+android.transition.Transition#captureEndValues captureEndValues()} method:</p>
+
+<pre>
+&#64;Override
+public void captureEndValues(TransitionValues transitionValues) {
+ captureValues(transitionValues);
+}
+</pre>
+
+<p>In this example, both the {@link android.transition.Transition#captureStartValues
+captureStartValues()} and {@link android.transition.Transition#captureEndValues captureEndValues()}
+methods invoke <code>captureValues()</code> to retrieve and store values. The view property
+that <code>captureValues()</code> retrieves is the same, but it has different values in the
+starting and ending scenes. The framework maintains separate maps for the starting and ending
+states of a view.</p>
+
+
+
+<h2 id="CreateAnimator">Create a Custom Animator</h2>
+
+<p>To animate the changes to a view between its state in the starting scene and its state in
+the ending scene, you provide an animator by overriding the {@link
+android.transition.Transition#createAnimator createAnimator()} method. When the
+framework calls this method, it passes in the scene root view and the {@link
+android.transition.TransitionValues} objects that contain the starting and ending values
+you captured.</p>
+
+<p>The number of times the framework calls the {@link
+android.transition.Transition#createAnimator createAnimator()} method depends on the changes that
+occur between the starting and ending scenes. For example, consider a fade out/fade in animation
+implemented as a custom transition. If the starting scene has five targets of which two are
+removed from the ending scene, and the ending scene has the three targets from the starting
+scene plus a new target, then the framework calls {@link
+android.transition.Transition#createAnimator createAnimator()} six times: three of the calls
+animate the fading out and fading in of the targets that stay in both scene objects; two more calls
+animate the fading out of the targets removed from the ending scene; and one call
+animates the fading in of the new target in the ending scene.</p>
+
+<p>For target views that exist on both the starting and ending scenes, the framework provides
+a {@link android.transition.TransitionValues} object for both the <code>startValues</code> and
+<code>endValues</code> arguments. For target views that only exist in the starting or the
+ending scene, the framework provides a {@link android.transition.TransitionValues} object
+for the corresponding argument and <code>null</code> for the other.</p>
+
+<p>To implement the {@link android.transition.Transition#createAnimator} method when you create
+a custom transition, use the view property values you captured to create an {@link
+android.animation.Animator} object and return it to the framework. For an example implementation,
+see the <a
+href="{@docRoot}samples/CustomTransition/src/com.example.android.customtransition/ChangeColor.html">
+<code>ChangeColor</code></a> class in the <a href="{@docRoot}samples/CustomTransition/index.html">
+CustomTransition</a> sample. For more information about property animators, see
+<a href="{@docRoot}guide/topics/graphics/prop-animation.html">Property Animation</a>.</p>
+
+
+
+<h2 id="Apply">Apply a Custom Transition</h2>
+
+<p>Custom transitions work the same as built-in transitions. You can apply a custom transition
+using a transition manager, as described in <a
+href="{@docRoot}training/transitions/transitions.html#Apply">Applying a Transition</a>.</p>
diff --git a/docs/html/training/transitions/index.jd b/docs/html/training/transitions/index.jd
new file mode 100644
index 0000000..53faa01
--- /dev/null
+++ b/docs/html/training/transitions/index.jd
@@ -0,0 +1,80 @@
+page.title=Animating Views Using Scenes and Transitions
+
+@jd:body
+
+<!-- Sidebox -->
+<div id="tb-wrapper">
+<div id="tb">
+ <h2>Dependencies and Prerequisites</h2>
+ <ul>
+ <li>Android 4.4.2 (API level 19) or higher</li>
+ </ul>
+ <h2>You should also read</h2>
+ <ul>
+ <li><a href="{@docRoot}guide/topics/ui/how-android-draws.html">
+ How Android Draws Views</a></li>
+ </ul>
+ <h2>Try it out</h2>
+ <ul>
+ <li><a href="{@docRoot}samples/BasicTransition/index.html">BasicTransition</a> sample</li>
+ <li><a href="{@docRoot}samples/CustomTransition/index.html">CustomTransition</a> sample</li>
+ </ul>
+</div>
+</div>
+
+<!-- Video box -->
+<a class="notice-developers-video wide" href="http://www.youtube.com/watch?v=S3H7nJ4QaD8">
+<div>
+ <h3>Video</h3>
+ <p>DevBytes: Android 4.4 Transitions</p>
+</div>
+</a>
+
+<p>The user interface of an activity often changes in response to user input and other events.
+For example, an activity that contains a form where users can type search queries can hide
+the form when the user submits it and show a list of search results in its place.</p>
+
+<p>To provide visual continuity in these situations, you can animate changes between
+different view hierarchies in your user interface. These animations give users feedback on
+their actions and help them learn how your app works.</p>
+
+<p>Android includes the <em>transitions framework</em>, which enables you to easily
+animate changes between two view hierarchies. The framework animates the views at runtime by
+changing some of their property values over time. The framework includes built-in animations
+for common effects and lets you create custom animations and transition lifecycle callbacks.</p>
+
+<p>This class teaches you to use the built-in animations in the transitions framework to
+animate changes between view hierarchies. This class also covers how to create custom
+animations.</p>
+
+<p class="note"><strong>Note:</strong> For Android versions earlier than 4.4.2 (API level 19)
+but greater than or equal to Android 4.0 (API level 14), use the <code>animateLayoutChanges</code>
+attribute to animate layouts. To learn more, see
+<a href="{@docRoot}guide/topics/graphics/prop-animation.html">Property Animation</a> and
+<a href="{@docRoot}training/animation/layout.html">Animating Layout Changes</a>.</p>
+
+
+<h2>Lessons</h2>
+
+<dl>
+<dt><a href="{@docRoot}training/transitions/overview.html">
+The Transitions Framework</a></dt>
+<dd>
+ Learn the main features and components of the transitions framework.
+</dd>
+<dt><a href="{@docRoot}training/transitions/scenes.html">
+Creating a Scene</a></dt>
+<dd>
+ Learn how to create a scene to store the state of a view hierarchy.
+</dd>
+<dt><a href="{@docRoot}training/transitions/transitions.html">
+Applying a Transition</a></dt>
+<dd>
+ Learn how to apply a transition between two scenes of a view hierarchy.
+</dd>
+<dt><a href="{@docRoot}training/transitions/custom-transitions.html">
+Creating Custom Transitions</a></dt>
+<dd>
+ Learn how to create other animation effects not included in the transitions framework.
+</dd>
+</dl>
diff --git a/docs/html/training/transitions/overview.jd b/docs/html/training/transitions/overview.jd
new file mode 100644
index 0000000..044cf16
--- /dev/null
+++ b/docs/html/training/transitions/overview.jd
@@ -0,0 +1,165 @@
+page.title=The Transitions Framework
+
+@jd:body
+
+<div id="tb-wrapper">
+<div id="tb">
+<h2>This lesson covers</h2>
+<ol>
+ <li><a href="#Overview">Overview</a></li>
+ <li><a href="#Scenes">Scenes</a></li>
+ <li><a href="#Transitions">Transitions</a></li>
+ <li><a href="#Limitations">Limitations</a></li>
+</ol>
+</div>
+</div>
+
+<p>Animating your app's user interface provides more than just visual appeal. Animations
+highlight changes and provide visual cues that help users learn how your app works.</p>
+
+<p>To help you animate a change between one view hierarchy and another, Android provides the
+transitions framework. This framework applies one or more animations to all the views in the
+hierarchies as it changes between them.</p>
+
+<p>The framework has the following features:</p>
+
+<dl>
+<dt><em>Group-level animations</em></dt>
+<dd>Applies one or more animation effects to all of the views in a view hierarchy.</dd>
+<dt><em>Transition-based animation</em></dt>
+<dd>Runs animations based on the changes between starting and ending view property values.</dd>
+<dt><em>Built-in animations</em></dt>
+<dd>Includes predefined animations for common effects such as fade out or movement.</dd>
+
+<!-- Figure 1 - Transitions video -->
+<div style="float:right;margin-left:30px;margin-top:10px">
+<div class="framed-nexus5-port-span-5" style="clear:left;">
+<video class="play-on-hover" height="442" autoplay="" poster="">
+<source src="{@docRoot}images/transitions/transition_sample_video.mp4" type="video/mp4">
+<source src="{@docRoot}images/transitions/transition_sample_video.ogv" type="video/ogg">
+<source src="{@docRoot}images/transitions/transition_sample_video.webm" type="video/webm">
+</video>
+</div>
+<p class="img-caption" style="margin-top:7px;margin-bottom:0px">
+<strong>Figure 1.</strong> Visual cues using user interface animation.</p>
+<div style="margin-top:5px;margin-bottom:20px;font-size:10pt" class="video-instructions">&nbsp;</div>
+</div>
+
+<dt><em>Resource file support</em></dt>
+<dd>Loads view hierarchies and built-in animations from layout resource files.</dd>
+<dt><em>Lifecycle callbacks</em></dt>
+<dd>Defines callbacks that provide finer control over the animation and hierarchy change
+process.</dd>
+</dl>
+
+
+
+<h2 id="Overview">Overview</h2>
+
+<p>The example in Figure 1 shows how an animation provides visual cues to help the user. As the
+app changes from its search entry screen to its search results screen, it fades out views that
+are no longer in use and fades in new views.</p>
+
+<p>This animation is an example of using the transitions framework. The framework
+animates changes to all the views in two view hierarchies. A view hierarchy can be as simple
+as a single view or as complex as a {@link android.view.ViewGroup} containing an elaborate
+tree of views. The framework animates each view by changing one or more of its property values
+over time between the initial or <em>starting</em> view hierarchy and the final or <em>ending</em>
+view hierarchy.</p>
+
+<p>The transitions framework works in parallel with view hierarchies and animations. The
+purpose of the framework is to store the state of view hierarchies, change between these
+hierarchies in order to modify the appearance of the device screen, and animate the change by
+storing and applying animation definitions.</p>
+
+<p>The diagram in Figure 2 illustrates the relationship between view hierarchies, framework
+objects, and animations:</p>
+
+<!-- Figure 2 - diagram -->
+<img src="{@docRoot}images/transitions/transitions_diagram.png"
+ width="506" height="234" alt="" style="margin-top:7px" />
+<p class="img-caption"><strong>Figure 2.</strong> Relationships in the transitions framework.</p>
+
+<p>The transitions framework provides abstractions for scenes, transitions, and transition
+managers. These are described in detail in the following sections. To use the framework, you
+create scenes for the view hierarchies in your app that you plan to change between. Next, you
+create a transition for each animation you want to use. To start the animation between two
+view hierarchies, you use a transition manager specifying the transition to use and the ending
+scene. This procedure is described in detail in the remaining lessons in this class.</p>
+
+
+
+<h2 id="Scenes">Scenes</h2>
+
+<p>A scene stores the state of a view hierarchy, including all its views and their property
+values. A view hierarchy can be a simple view or a complex tree of views and child layouts.
+Storing the view hierarchy state in a scene enables you to transition into that state from
+another scene. The framework provides the {@link android.transition.Scene} class to represent
+a scene.</p>
+
+<p>The transitions framework lets you create scenes from layout resource files or from
+{@link android.view.ViewGroup} objects in your code. Creating a scene in your code is useful
+if you generated a view hierarchy dynamically or if you are modifying it at runtime.</p>
+
+<p>In most cases, you do not create a starting scene explicitly. If you have applied a
+transition, the framework uses the previous ending scene as the starting scene for any
+subsequent transitions. If you have not applied a transition, the framework collects information
+about the views from the current state of the screen.</p>
+
+<p>A scene can also define its own actions that run when you make a scene change. For example,
+this feature is useful for cleaning up view settings after you transition to a scene.</p>
+
+<p>In addition to the view hierarchy and its property values, a scene also stores a reference
+to the parent of the view hierarchy. This root view is called a <strong>scene root</strong>.
+Changes to the scene and animations that affect the scene occur within the scene root.</p>
+
+<p>To learn how to create scenes, see
+<a href="{@docRoot}training/transitions/scenes.html">Creating a Scene</a>.</p>
+
+
+
+<h2 id="Transitions">Transitions</h2>
+
+<p>In the transitions framework, animations create a series of frames that depict a change
+between the view hierarchies in the starting and ending scenes. Information about the animation
+is stored in a {@link android.transition.Transition} object. To run the animation, you apply the
+transition using a {@link android.transition.TransitionManager} instance. The framework can
+transition between two different scenes or transition to a different state for the current
+scene.</p>
+
+<p>The framework includes a set of built-in transitions for commonly-used animation effects,
+such as fading and resizing views. You can also define your own custom transitions to create
+an animation effect using the APIs in the animations framework. The transitions framework also
+enables you to combine different animation effects in a transition set that contains a group
+of individual built-in or custom transitions.</p>
+
+<p>The transition lifecycle is similar to the activity lifecycle, and it represents the
+transition states that the framework monitors between the start and the completion of an
+animation. At important lifecycle states, the framework invokes callback methods that you can
+implement to make adjustments to your user interface at different phases of the transition.</p>
+
+<p>To learn more about transitions, see
+<a href="{@docRoot}training/transitions/transitions.html">Applying a Transition</a> and
+<a href="{@docRoot}training/transitions/custom-transitions.html">Creating Custom
+Transitions</a>.</p>
+
+
+
+<h2 id="Limitations">Limitations</h2>
+
+<p>This section lists some known limitations of the transitions framework:</p>
+
+<ul>
+<li>Animations applied to a {@link android.view.SurfaceView} may not appear correctly.
+{@link android.view.SurfaceView} instances are updated from a non-UI thread, so the updates
+may be out of sync with the animations of other views.</li>
+<li>Some specific transition types may not produce the desired animation effect when applied
+to a {@link android.view.TextureView}.</li>
+<li>Classes that extend {@link android.widget.AdapterView}, such as
+{@link android.widget.ListView}, manage their child views in ways that are incompatible with
+the transitions framework. If you try to animate a view based on
+{@link android.widget.AdapterView}, the device display may hang.</li>
+<li>If you try to resize a {@link android.widget.TextView} with an animation, the text will
+pop to a new location before the object has completely resized. To avoid this problem, do not
+animate the resizing of views that contain text.</li>
+</ul>
diff --git a/docs/html/training/transitions/scenes.jd b/docs/html/training/transitions/scenes.jd
new file mode 100644
index 0000000..4bf7d0e
--- /dev/null
+++ b/docs/html/training/transitions/scenes.jd
@@ -0,0 +1,211 @@
+page.title=Creating a Scene
+
+@jd:body
+
+<div id="tb-wrapper">
+<div id="tb">
+<h2>This lesson teaches you to</h2>
+<ol>
+ <li><a href="#FromLayout">Create a Scene From a Layout Resource</a></li>
+ <li><a href="#FromCode">Create a Scene in Your Code</a></li>
+ <li><a href="#Actions">Create Scene Actions</a></li>
+</ol>
+</div>
+</div>
+
+<p>Scenes store the state of a view hierarchy, including all its views and their property
+values. The transitions framework can run animations between a starting and an ending scene.
+The starting scene is often determined automatically from the current state of the user
+interface. For the ending scene, the framework enables you to create a scene from a layout
+resource file or from a group of views in your code.</p>
+
+<p>This lesson shows you how to create scenes in your app and how to define scene actions.
+The next lesson shows you how to transition between two scenes.</p>
+
+<p class="note"><strong>Note:</strong> The framework can animate changes in a single view
+hierarchy without using scenes, as described in
+<a href="{@docRoot}training/transitions/transitions.html#NoScenes">Apply a Transition Without
+Scenes</a>. However, understanding this lesson is essential to work with transitions.</p>
+
+
+
+<h2 id="FromLayout">Create a Scene From a Layout Resource</h2>
+
+<p>You can create a {@link android.transition.Scene} instance directly from a layout resource
+file. Use this technique when the view hierarchy in the file is mostly static. The resulting
+scene represents the state of the view hierarchy at the time you created the
+{@link android.transition.Scene} instance. If you change the view hierarchy, you have to
+recreate the scene. The framework creates the scene from the entire view hierarchy in the
+file; you can not create a scene from part of a layout file.</p>
+
+<p>To create a {@link android.transition.Scene} instance from a layout resource file, retrieve
+the scene root from your layout as a {@link android.view.ViewGroup} instance and then call the
+{@link android.transition.Scene#getSceneForLayout Scene.getSceneForLayout()} method with the
+scene root and the resource ID of the layout file that contains the view hierarchy for the
+scene.</p>
+
+<h3>Define Layouts for Scenes</h3>
+
+<p>The code snippets in the rest of this section show you how to create two different scenes
+with the same scene root element. The snippets also demonstrate that you can load multiple
+unrelated {@link android.transition.Scene} objects without implying that they are related to
+each other.</p>
+
+<p>The example consists of the following layout definitions:</p>
+
+<ul>
+<li>The main layout of an activity with a text label and a child layout.</li>
+<li>A relative layout for the first scene with two text fields.</li>
+<li>A relative layout for the second scene with the same two text fields in different order.</li>
+</ul>
+
+<p>The example is designed so that all of the animation occurs within the child layout of the
+main layout for the activity. The text label in the main layout remains static.</p>
+
+<p>The main layout for the activity is defined as follows:</p>
+
+<p class="code-caption">res/layout/activity_main.xml</p>
+
+<pre>
+&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/master_layout">
+ &lt;TextView
+ android:id="@+id/title"
+ ...
+ android:text="Title"/>
+ &lt;FrameLayout
+ android:id="@+id/scene_root">
+ &lt;include layout="@layout/a_scene" />
+ &lt;/FrameLayout>
+&lt;/LinearLayout>
+</pre>
+
+<p>This layout definition contains a text field and a child layout for the scene root. The
+layout for the first scene is included in the main layout file. This allows the app to display
+it as part of the initial user interface and also to load it into a scene, since the framework
+can load only a whole layout file into a scene.</p>
+
+<p>The layout for the first scene is defined as follows:</p>
+
+<p class="code-caption">res/layout/a_scene.xml</p>
+
+<pre>
+&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/scene_container"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent" >
+ &lt;TextView
+ android:id="@+id/text_view1
+ android:text="Text Line 1" />
+ &lt;TextView
+ android:id="@+id/text_view2
+ android:text="Text Line 2" />
+&lt;/RelativeLayout>
+</pre>
+
+<p>The layout for the second scene contains the same two text fields (with the same IDs)
+placed in a different order and is defined as follows:</p>
+
+<p class="code-caption">res/layout/another_scene.xml</p>
+
+<pre>
+&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/scene_container"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent" >
+ &lt;TextView
+ android:id="@+id/text_view2
+ android:text="Text Line 2" />
+ &lt;TextView
+ android:id="@+id/text_view1
+ android:text="Text Line 1" />
+&lt;/RelativeLayout>
+</pre>
+
+<h3>Generate Scenes from Layouts</h3>
+
+<p>After you create definitions for the two relative layouts, you can obtain an scene for
+each of them. This enables you to later transition between the two UI configurations.
+To obtain a scene, you need a reference to the scene root and the layout resource ID.</p>
+
+<p>The following code snippet shows you how to get a reference to the scene root and create
+two {@link android.transition.Scene} objects from the layout files:</p>
+
+<pre>
+Scene mAScene;
+Scene mAnotherScene;
+
+// Create the scene root for the scenes in this app
+mSceneRoot = (ViewGroup) findViewById(R.id.scene_root);
+
+// Create the scenes
+mAScene = Scene.getSceneForLayout(mSceneRoot, R.layout.a_scene, this);
+mAnotherScene =
+ Scene.getSceneForLayout(mSceneRoot, R.layout.another_scene, this);
+</pre>
+
+<p>In the app, there are now two {@link android.transition.Scene} objects based on view
+hierarchies. Both scenes use the scene root defined by the
+{@link android.widget.FrameLayout} element in <code>res/layout/activity_main.xml</code>.</p>
+
+
+
+<h2 id="FromCode">Create a Scene in Your Code</h2>
+
+<p>You can also create a {@link android.transition.Scene} instance in your code from a
+{@link android.view.ViewGroup} object. Use this technique when you modify the view hierarchies
+directly in your code or when you generate them dynamically.</p>
+
+<p>To create a scene from a view hierarchy in your code, use the
+{@link android.transition.Scene#Scene(android.view.ViewGroup, android.view.View) Scene(sceneRoot, viewHierarchy)}
+constructor. Calling this constructor is equivalent to calling the
+{@link android.transition.Scene#getSceneForLayout Scene.getSceneForLayout()} method when you
+have already inflated a layout file.</p>
+
+<p>The following code snippet demonstrates how to create a {@link android.transition.Scene}
+instance from the scene root element and the view hierarchy for the scene in your code:</p>
+
+<pre>
+Scene mScene;
+
+// Obtain the scene root element
+mSceneRoot = (ViewGroup) mSomeLayoutElement;
+
+// Obtain the view hierarchy to add as a child of
+// the scene root when this scene is entered
+mViewHierarchy = (ViewGroup) someOtherLayoutElement;
+
+// Create a scene
+mScene = new Scene(mSceneRoot, mViewHierarchy);
+</pre>
+
+
+
+<h2 id="Actions">Create Scene Actions</h2>
+
+<p>The framework enables you to define custom scene actions that the system runs when entering
+or exiting a scene. In many cases, defining custom scene actions is not necessary, since the
+framework animates the change between scenes automatically.</p>
+
+<p>Scene actions are useful for handling these cases:</p>
+
+<ul>
+<li>Animate views that are not in the same hierarchy. You can animate views for both the
+starting and ending scenes using exit and entry scene actions.</li>
+<li>Animate views that the transitions framework cannot animate automatically, such as
+{@link android.widget.ListView} objects. For more information, see
+<a href="{@docRoot}training/transitions/overview.html#Limitations">Limitations</a>.</li>
+</ul>
+
+<p>To provide custom scene actions, define your actions as {@link java.lang.Runnable} objects
+and pass them to the {@link android.transition.Scene#setExitAction Scene.setExitAction()} or
+{@link android.transition.Scene#setEnterAction Scene.setEnterAction()} methods. The framework
+calls the {@link android.transition.Scene#setExitAction setExitAction()} method on the starting
+scene before running the transition animation and the {@link
+android.transition.Scene#setEnterAction setEnterAction()} method on the ending scene after
+running the transition animation.</p>
+
+<p class="note"><strong>Note:</strong> Do not use scene actions to pass data between views in
+the starting and ending scenes. For more information, see
+<a href="{@docRoot}training/transitions/transitions.html#Callbacks">Defining Transition
+Lifecycle Callbacks</a>.</p>
diff --git a/docs/html/training/transitions/transitions.jd b/docs/html/training/transitions/transitions.jd
new file mode 100644
index 0000000..489e291
--- /dev/null
+++ b/docs/html/training/transitions/transitions.jd
@@ -0,0 +1,315 @@
+page.title=Applying a Transition
+
+@jd:body
+
+<div id="tb-wrapper">
+<div id="tb">
+<h2>This lesson teaches you to</h2>
+<ol>
+ <li><a href="#Create">Create a Transition</a></li>
+ <li><a href="#Apply">Apply a Transition</a></li>
+ <li><a href="#Targets">Choose Specific Target Views</a></li>
+ <li><a href="#Multiple">Specify Multiple Transitions</a></li>
+ <li><a href="#NoScenes">Apply a Transition Without Scenes</a></li>
+ <li><a href="#Callbacks">Define Transition Lifecycle Callbacks</a></li>
+</ol>
+</div>
+</div>
+
+<p>In the transitions framework, animations create a series of frames that depict a change
+between the view hierarchies in the starting and ending scenes. The framework represents
+these animations as transition objects, which contain information about an animation. To
+run an animation, you provide the transition to use and the ending scene to a transition
+manager.</p>
+
+<p>This lesson teaches you run an animation between two scenes using built-in transitions
+to move, resize, and fade views. The next lesson shows you how to define custom transitions.</p>
+
+
+
+<h2 id="Create">Create a Transition</h2>
+
+<p>In the previous lesson, you learned how to create scenes that represent the state of
+different view hierarchies. Once you have defined the starting scene and the ending scene you
+want to change between, you need to create a {@link android.transition.Transition} object
+that defines an animation. The framework enables you to specify a built-in transition in a
+resource file and inflate it in your code or to create an instance of a built-in transition
+directly in your code.</p>
+
+<!-- Built in transition table -->
+<p class="table-caption" id="table1"><strong>Table 1.</strong> Built-in transition types.</p>
+<table>
+<tr>
+ <th scope="col">Class</th>
+ <th scope="col">Tag</th>
+ <th scope="col">Attributes</th>
+ <th scope="col">Effect</th>
+</tr>
+<tr>
+ <td><code><a href="/reference/android/transition/AutoTransition.html">AutoTransition</a></code></td>
+ <td>&lt;autoTransition/&gt;</td>
+ <td style="text-align=center;"> - </td>
+ <td>Default transition. Fade out, move and resize, and fade in views, in that order.</td>
+</tr>
+<tr>
+ <td><code><a href="/reference/android/transition/Fade.html">Fade</a></code></td>
+ <td>&lt;fade/&gt;</td>
+ <td><code>android:fadingMode="[fade_in |<br> fade_out |<br> fade_in_out]"</code></td>
+ <td>
+ <code>fade_in</code> fades in views<br>
+ <code>fade_out</code> fades out views<br>
+ <code>fade_in_out</code> (default) does a <code>fade_out</code> followed by a <code>fade_in</code>.
+ </td>
+</tr>
+<tr>
+ <td><code><a href="/reference/android/transition/ChangeBounds.html">ChangeBounds</a></code></td>
+ <td>&lt;changeBounds/&gt;</td>
+ <td style="text-align=center;"> - </td>
+ <td>Moves and resizes views.</td>
+</tr>
+</table>
+
+
+<h3 id="FromFile">Create a transition instance from a resource file</h3>
+
+<p>This technique enables you to modify your transition definition without having to change
+the code of your activity. This technique is also useful to separate complex transition
+definitions from your application code, as shown in <a href="#Multiple">Specify Multiple
+Transitions</a>.</p>
+
+<p>To specify a built-in transition in a resource file, follow these steps:</p>
+
+<ol>
+<li>Add the <code>res/transition/</code> directory to your project.</li>
+<li>Create a new XML resource file inside this directory.</li>
+<li>Add an XML node for one of the built-in transitions.</li>
+</ol>
+
+<p>For example, the following resource file specifies the {@link android.transition.Fade}
+transition:</p>
+
+<p class="code-caption">res/transition/fade_transition.xml</p>
+
+<pre>
+&lt;fade xmlns:android="http://schemas.android.com/apk/res/android" />
+</pre>
+
+<p>The following code snippet shows how to inflate a {@link android.transition.Transition}
+instance inside your activity from a resource file:</p>
+
+<pre>
+Transition mFadeTransition =
+ TransitionInflater.from(this).
+ inflateTransition(R.transition.fade_transition);
+</pre>
+
+
+<h3 id="FromCode">Create a transition instance in your code</h3>
+
+<p>This technique is useful for creating transition objects dynamically if you modify the user
+interface in your code, and to create simple built-in transition instances with few or
+no parameters.</p>
+
+<p>To create an instance of a built-in transition, invoke one of the public constructors in
+the subclasses of the {@link android.transition.Transition} class. For example, the following
+code snippet creates an instance of the {@link android.transition.Fade} transition:</p>
+
+<pre>
+Transition mFadeTransition = new Fade();
+</pre>
+
+
+
+<h2 id="Apply">Apply a Transition</h2>
+
+<p>You typically apply a transition to change between different view hierarchies in response
+to an event, such as a user action. For example, consider a search app: when the user enters
+a search term and clicks the search button, the app changes to the scene that represents the
+results layout while applying a transition that fades out the search button and fades in the
+search results.</p>
+
+<p>To make a scene change while applying a transition in response to some event in your
+activity, call the {@link android.transition.TransitionManager#go TransitionManager.go()}
+static method with the ending scene and the transition instance to use for the animation,
+as shown in the following snippet:</p>
+
+<pre>
+TransitionManager.go(mEndingScene, mFadeTransition);
+</pre>
+
+<p>The framework changes the view hierarchy inside the scene root with the view hierarchy
+from the ending scene while running the animation specified by the transition instance. The
+starting scene is the ending scene from the last transition. If there was no previous
+transition, the starting scene is determined automatically from the current state of the
+user interface.</p>
+
+<p>If you do not specify a transition instance, the transition manager can apply an automatic
+transition that does something reasonable for most situations. For more information, see the
+API reference for the {@link android.transition.TransitionManager} class.</p>
+
+
+
+<h2 id="Targets">Choose Specific Target Views</h2>
+
+<p>The framework applies transitions to all views in the starting and ending scenes by
+default. In some cases, you may only want to apply an animation to a subset of views in a
+scene. For example, the framework does not support animating changes to
+{@link android.widget.ListView} objects, so you should not try to animate them during a
+transition. The framework enables you to select specific views you want to animate.</p>
+
+<p>Each view that the transition animates is called a <em>target</em>. You can only
+select targets that are part of the view hierarchy associated with a scene.</p>
+
+<p>To remove one or more views from the list of targets, call the {@link
+android.transition.Transition#removeTarget removeTarget()} method before starting
+the transition. To add only the views you specify to the list of targets, call the
+{@link android.transition.Transition#addTarget addTarget()} method. For more
+information, see the API reference for the {@link android.transition.Transition} class.</p>
+
+
+
+<h2 id="Multiple">Specify Multiple Transitions</h2>
+
+<p>To get the most impact from an animation, you should match it to the type of changes
+that occur between the scenes. For example, if you are removing some views and adding others
+between scenes, a fade out/fade in animation provides a noticeable indication that some views
+are no longer available. If you are moving views to different points on the screen, a better
+choice would be to animate the movement so that users notice the new location of the views.</p>
+
+<p>You do not have to choose only one animation, since the transitions framework enables you
+to combine animation effects in a transition set that contains a group of individual built-in
+or custom transitions.</p>
+
+<p>To define a transition set from a collection of transitions in XML, create a resource file
+in the <code>res/transitions/</code> directory and list the transitions under the
+<code>transitionSet</code> element. For example, the following snippet shows how to specify a
+transition set that has the same behaviour as the {@link android.transition.AutoTransition}
+class:</p>
+
+<pre>
+&lt;transitionSet xmlns:android="http://schemas.android.com/apk/res/android"
+ android:transitionOrdering="sequential">
+ &lt;fade android:fadingMode="fade_out" />
+ &lt;changeBounds />
+ &lt;fade android:fadingMode="fade_in" />
+&lt;/transitionSet>
+</pre>
+
+<p>To inflate the transition set into a {@link android.transition.TransitionSet} object in
+your code, call the {@link android.transition.TransitionInflater#from TransitionInflater.from()}
+method in your activity. The {@link android.transition.TransitionSet} class extends from the
+{@link android.transition.Transition} class, so you can use it with a transition manager just
+like any other {@link android.transition.Transition} instance.</p>
+
+
+
+<h2 id="NoScenes">Apply a Transition Without Scenes</h2>
+
+<p>Changing view hierarchies is not the only way to modify your user interface. You can also
+make changes by adding, modifying, and removing child views within the current hierarchy. For
+example, you can implement a search interaction with just a single layout. Start with the
+layout showing a search entry field and a search icon. To change the user interface to show
+the results, remove the search button when the user clicks it by calling the {@link
+android.view.ViewGroup#removeView ViewGroup.removeView()} method, and add the search results by
+calling {@link android.view.ViewGroup#addView ViewGroup.addView()} method.</p>
+
+<p>You may want to use this approach if the alternative is to have two hierarchies that are
+nearly identical. Rather than having to create and maintain two separate layout files for a
+minor difference in the user interface, you can have one layout file containing a view
+hierarchy that you modify in code.</p>
+
+<p>If you make changes within the current view hierarchy in this fashion, you do not need to
+create a scene. Instead, you can create and apply a transition between two states of a view
+hierarchy using a <em>delayed transition</em>. This feature of the transitions framework
+starts with the current view hierarchy state, records changes you make to its views, and applies
+a transition that animates the changes when the system redraws the user interface.</p>
+
+<p>To create a delayed transition within a single view hierarchy, follow these steps:</p>
+
+<ol>
+<li>When the event that triggers the transition occurs, call the {@link
+android.transition.TransitionManager#beginDelayedTransition
+TransitionManager.beginDelayedTransition()} method providing the parent view of all the views
+you want to change and the transition to use. The framework stores the current state of the
+child views and their property values.</li>
+<li>Make changes to the child views as required by your use case. The framework records
+the changes you make to the child views and their properties.</li>
+<li>When the system redraws the user interface according to your changes, the framework
+animates the changes between the original state and the new state.</li>
+</ol>
+
+<p>The following example shows how to animate the addition of a text view to a view hierarchy
+using a delayed transition. The first snippet shows the layout definition file:</p>
+
+<p class="code-caption">res/layout/activity_main.xml</p>
+
+<pre>
+&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/mainLayout"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent" >
+ &lt;EditText
+ android:id="@+id/inputText"
+ android:layout_alignParentLeft="true"
+ android:layout_alignParentTop="true"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content" />
+ ...
+&lt;/RelativeLayout>
+</pre>
+
+<p>The next snippet shows the code that animates the addition of the text view:</p>
+
+<p class="code-caption">MainActivity.java</p>
+
+<pre>
+private TextView mLabelText;
+private Fade mFade;
+private ViewGroup mRootView;
+...
+
+// Load the layout
+this.setContentView(R.layout.activity_main);
+...
+
+// Create a new TextView and set some View properties
+mLabelText = new TextView();
+mLabelText.setText("Label").setId("1");
+
+// Get the root view and create a transition
+mRootView = (ViewGroup) findViewById(R.id.mainLayout);
+mFade = new Fade(IN);
+
+// Start recording changes to the view hierarchy
+TransitionManager.beginDelayedTransition(mRootView, mFade);
+
+// Add the new TextView to the view hierarchy
+mRootView.addView(mLabelText);
+
+// When the system redraws the screen to show this update,
+// the framework will animate the addition as a fade in
+</pre>
+
+
+
+<h2 id="Callbacks">Define Transition Lifecycle Callbacks</h2>
+
+<p>The transition lifecycle is similar to the activity lifecycle. It represents the transition
+states that the framework monitors during the time between a call to the {@link
+android.transition.TransitionManager#go TransitionManager.go()} method and the completion of
+the animation. At important lifecycle states, the framework invokes callbacks defined by
+the {@link android.transition.Transition.TransitionListener TransitionListener}
+interface.</p>
+
+<p>Transition lifecycle callbacks are useful, for example, for copying a view property value
+from the starting view hierarchy to the ending view hierarchy during a scene change. You
+cannot simply copy the value from its starting view to the view in the ending view hierarchy,
+because the ending view hierarchy is not inflated until the transition is completed.
+Instead, you need to store the value in a variable and then copy it into the ending view
+hierarchy when the framework has finished the transition. To get notified when the transition
+is completed, you can implement the {@link
+android.transition.Transition.TransitionListener#onTransitionEnd
+TransitionListener.onTransitionEnd()} method in your activity.</p>
+
+<p>For more information, see the API reference for the {@link
+android.transition.Transition.TransitionListener TransitionListener} class.</p>
diff --git a/docs/html/training/tv/discovery/index.jd b/docs/html/training/tv/discovery/index.jd
index f22ca67..066dfb3 100644
--- a/docs/html/training/tv/discovery/index.jd
+++ b/docs/html/training/tv/discovery/index.jd
@@ -23,7 +23,7 @@ startpage=true
<p>
TV devices offer many entertainment options for users. They have thousands of content options
from apps and related content services. At the same time, most users prefer to use TVs with the
- least amount of input possible. With the amount of choice available to users, it is important for
+ least amount of input possible. With the number of choices available to users, it is important for
app developers to provide quick and easy paths for users to discover and enjoy your content.
</p>
@@ -44,7 +44,8 @@ startpage=true
<dt><b><a href="recommendations.html">Recommending TV Content</a></b></dt>
<dd>Learn how to recommend content for users so that it appears in the recommendations row
on the home screen of a TV device.</dd>
-
+ <dt><b><a href="searchable.html">Making TV Apps Searchable</a></b></dt>
+ <dd>Learn how to make your content searchable from the Android TV home screen.</dd>
<dt><b><a href="in-app-search.html">Searching within TV Apps</a></b></dt>
<dd>Learn how to use a built-for-TV user interface for searching within your app.</dd>
</dl>
diff --git a/docs/html/training/tv/discovery/recommendations.jd b/docs/html/training/tv/discovery/recommendations.jd
index d348c14..a74ee56 100644
--- a/docs/html/training/tv/discovery/recommendations.jd
+++ b/docs/html/training/tv/discovery/recommendations.jd
@@ -61,11 +61,6 @@ trainingnavtop=true
create a recommendation service for your application:
</p>
-
-<p class="code-caption">
- <a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/java/com/example/android/tvleanback/UpdateRecommendationsService.java" target="_blank">
- UpdateRecommendationsService.java</a>
-</p>
<pre>
public class UpdateRecommendationsService extends IntentService {
private static final String TAG = "UpdateRecommendationsService";
@@ -136,10 +131,6 @@ public class UpdateRecommendationsService extends IntentService {
app manifest. The following code snippet illustrates how to declare this class as a service:
</p>
-<p class="code-caption">
- <a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/AndroidManifest.xml" target="_blank">
- AndroidManifest.xml</a>
-</p>
<pre>
&lt;manifest ... &gt;
&lt;application ... &gt;
@@ -160,6 +151,11 @@ the recommendations to appear at the end of the recommendations row. Once a cont
movie, has been played, <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#Removing">
remove it</a> from the recommendations.</p>
+<p>The order of an app's recommendations is preserved according to the order in which the app
+provides them. The framework interleaves app recommendations based on recommendation quality,
+as measured by user behavior. Better recommendations make an app's recommendations more likely
+to appear near the front of the list.</p>
+
<h2 id="build">Build Recommendations</h2>
<p>
@@ -175,10 +171,6 @@ remove it</a> from the recommendations.</p>
the builder pattern described as follows. First, you set the values of the recommendation card
elements.</p>
-<p class="code-caption">
- <a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/java/com/example/android/tvleanback/RecommendationBuilder.java" target="_blank">
- RecommendationBuilder.java</a>
-</p>
<pre>
public class RecommendationBuilder {
...
@@ -221,13 +213,9 @@ public class RecommendationBuilder {
</p>
<p>
- The following code example demonstrates how to build a recommendation, and post it to the manager.
+ The following code example demonstrates how to build a recommendation.
</p>
-<p class="code-caption">
- <a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/java/com/example/android/tvleanback/RecommendationBuilder.java" target="_blank">
- RecommendationBuilder.java</a>
-</p>
<pre>
public class RecommendationBuilder {
...
@@ -250,8 +238,6 @@ public class RecommendationBuilder {
.setExtras(extras))
.build();
- mNotificationManager.notify(mId, notification);
- mNotificationManager = null;
return notification;
}
}
@@ -267,10 +253,6 @@ public class RecommendationBuilder {
every half hour:
</p>
-<p class="code-caption">
- <a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/java/com/example/android/tvleanback/BootupActivity.java" target="_blank">
- BootupActivity.java</a>
-</p>
<pre>
public class BootupActivity extends BroadcastReceiver {
private static final String TAG = "BootupActivity";
@@ -307,10 +289,6 @@ public class BootupActivity extends BroadcastReceiver {
following sample code demonstrates how to add this configuration to the manifest:
</p>
-<p class="code-caption">
- <a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/AndroidManifest.xml" target="_blank">
- AndroidManifest.xml</a>
-</p>
<pre>
&lt;manifest ... &gt;
&lt;application ... &gt;
@@ -330,3 +308,12 @@ public class BootupActivity extends BroadcastReceiver {
requests the {@link android.Manifest.permission#RECEIVE_BOOT_COMPLETED} permission.
For more information, see {@link android.content.Intent#ACTION_BOOT_COMPLETED}.
</p>
+
+<p>In your recommendation service class' {@link android.app.IntentService#onHandleIntent(android.content.Intent)
+onHandleIntent()}
+method, post the recommendation to the manager as follows:</p>
+
+<pre>
+Notification notification = notificationBuilder.build();
+mNotificationManager.notify(id, notification);
+</pre>
diff --git a/docs/html/training/tv/discovery/searchable.jd b/docs/html/training/tv/discovery/searchable.jd
index 5d3b9e3..27a1c33 100644
--- a/docs/html/training/tv/discovery/searchable.jd
+++ b/docs/html/training/tv/discovery/searchable.jd
@@ -109,8 +109,6 @@ view for the content, along with links to the apps of other providers. This is d
<p>Your application's database class might define the columns as follows:</p>
-<p class="code-caption"><a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/java/com/example/android/tvleanback/VideoDatabase.java#L41" target="_blank">
-VideoDatabase.java</a></p>
<pre>
public class VideoDatabase {
//The columns we'll include in the video database table
@@ -136,8 +134,6 @@ public class VideoDatabase {
<p>When you build the map from the {@link android.app.SearchManager} columns to your data fields, you
must also specify the {@link android.provider.BaseColumns#_ID} to give each row a unique ID.</p>
-<p class="code-caption"><a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/java/com/example/android/tvleanback/VideoDatabase.java#L83" target="_blank">
-VideoDatabase.java</a></p>
<pre>
...
private static HashMap<String, String> buildColumnMap() {
@@ -195,8 +191,6 @@ java.lang.String[], java.lang.String, java.lang.String[], java.lang.String) quer
provider searches your suggestion data and returns a {@link android.database.Cursor} that points to
the rows you have designated for suggestions.</p>
-<p class="code-caption"><a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/java/com/example/android/tvleanback/VideoContentProvider.java" target="_blank">
-VideoContentProvider.java</a></p>
<pre>
&#64;Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
@@ -248,8 +242,6 @@ provider includes the {@code android:searchSuggestAuthority} attribute to tell t
namespace of your content provider. Also, you must set its {@code android:exported} attribute to
{@code "true"} so that the Android global search can use the results returned from it.</p>
-<p class="code-caption"><a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/AndroidManifest.xml" target="_blank">
-AndroidManifest.xml</a></p>
<pre>
&lt;provider android:name="com.example.android.tvleanback.VideoContentProvider"
android:authorities="com.example.android.tvleanback"
@@ -294,8 +286,6 @@ question mark ({@code ?}) value is replaced with the query text.</p>
<a href="{@docRoot}guide/topics/search/searchable-config.html">{@code searchable.xml}</a>
file:</p>
-<p class="code-caption"><a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/res/xml/searchable.xml" target="_blank">
-Searchable.xml</a></p>
<pre>
&lt;searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/search_label"
@@ -320,8 +310,6 @@ intent searches the repository for columns with the given word in their values,
of content items with those columns. In your {@code AndroidManifest.xml} file, you designate the
activity which handles the {@link android.content.Intent#ACTION_SEARCH} intent like this:
-<p class="code-caption"><a href="https://github.com/googlesamples/androidtv-Leanback/blob/master/app/src/main/AndroidManifest.xml" target="_blank">
-AndroidManifest.xml</a></p>
<pre>
...
&lt;activity
@@ -361,8 +349,12 @@ Suggestions</a> and mapped the {@link android.app.SearchManager#SUGGEST_COLUMN_T
{@link android.app.SearchManager#SUGGEST_COLUMN_CONTENT_TYPE}, and
{@link android.app.SearchManager#SUGGEST_COLUMN_PRODUCTION_YEAR} fields as described in
<a href="#columns">Identify Columns</a>, a <a href="{@docRoot}training/app-indexing/deep-linking.html">
-deep link</a> to your content appears in the details screen that launches when the user selects a
-search result.</p>
+deep link</a> to a watch action for your content appears in the details screen that launches when
+the user selects a search result, as shown in figure 1.</p>
+
+<img itemprop="image" src="{@docRoot}images/tv/deep-link.png" alt="Deep link in the details screen"/>
+<p class="img-caption"><b>Figure 1.</b> The details screen displays a deep link for the
+Videos by Google (Leanback) sample app. Sintel: &copy; copyright Blender Foundation, www.sintel.org.</p>
<p>When the user selects the link for your app, identified by the "Available On" button in the
details screen, the system launches the activity which handles the {@link android.content.Intent#ACTION_VIEW}
diff --git a/docs/html/training/tv/playback/card.jd b/docs/html/training/tv/playback/card.jd
new file mode 100644
index 0000000..8ac75fd
--- /dev/null
+++ b/docs/html/training/tv/playback/card.jd
@@ -0,0 +1,156 @@
+page.title=Providing a Card View
+page.tags="card"
+
+trainingnavtop=true
+
+@jd:body
+
+<div id="tb-wrapper">
+<div id="tb">
+ <h2>This lesson teaches you to</h2>
+ <ol>
+ <li><a href="#presenter">Create a Card Presenter</a></li>
+ <li><a href="#card-view">Create a Card View</a></li>
+ </ol>
+ <h2>Try it out</h2>
+ <ul>
+ <li><a class="external-link" href="https://github.com/googlesamples/androidtv-Leanback">Android
+ Leanback sample app</a></li>
+ </ul>
+</div>
+</div>
+
+<p>In the previous lesson, you created a catalog browser, implemented in a browse fragment, that
+displays a list of media items. In this lesson, you create the card views for your media items and
+present them in the browse fragment.</p>
+
+<p>The {@link android.support.v17.leanback.widget.BaseCardView} class and subclasses display the meta
+data associated with a media item. The {@link android.support.v17.leanback.widget.ImageCardView}
+class used in this lesson displays an image for the content along with the media item's title.</p>
+
+<p>This lesson describes code from the <a href="https://github.com/googlesamples/androidtv-Leanback">
+Android Leanback sample app</a>, available on GitHub. Use this sample code to start your own
+app.</p>
+
+<img itemprop="image" src="{@docRoot}images/tv/app-browse.png" alt="App main screen"/>
+<p class="img-caption"><b>Figure 1.</b> The <a href="https://github.com/googlesamples/androidtv-Leanback">
+Leanback sample app</a> browse fragment with a card presenter displaying card view objects.</p>
+
+<h2 id="presenter">Create a Card Presenter</h2>
+
+<p>A {@link android.support.v17.leanback.widget.Presenter} generates views and binds objects to them
+on demand. In the browse fragment where your app presents its content to the user, you create a
+{@link android.support.v17.leanback.widget.Presenter} for the content cards and pass it to the adapter
+that adds the content to the screen. In the following code, the <code>CardPresenter</code> is created
+in the {@link android.support.v4.app.LoaderManager.LoaderCallbacks#onLoadFinished(android.support.v4.content.Loader, java.lang.Object) onLoadFinished()}
+callback of the {@link android.support.v4.app.LoaderManager}.</p>
+
+<pre>
+&#64;Override
+public void onLoadFinished(Loader&lt;HashMap&lt;String, List&lt;Movie&gt;&gt;&gt; arg0,
+ HashMap&lt;String, List&lt;Movie&gt;&gt; data) {
+
+ mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
+ CardPresenter cardPresenter = new CardPresenter();
+
+ int i = 0;
+
+ for (Map.Entry&lt;String, List&lt;Movie&gt;&gt; entry : data.entrySet()) {
+ ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(cardPresenter);
+ List&lt;Movie&gt; list = entry.getValue();
+
+ for (int j = 0; j &lt; list.size(); j++) {
+ listRowAdapter.add(list.get(j));
+ }
+ HeaderItem header = new HeaderItem(i, entry.getKey(), null);
+ i++;
+ mRowsAdapter.add(new ListRow(header, listRowAdapter));
+ }
+
+ HeaderItem gridHeader = new HeaderItem(i, getString(R.string.more_samples),
+ null);
+
+ GridItemPresenter gridPresenter = new GridItemPresenter();
+ ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(gridPresenter);
+ gridRowAdapter.add(getString(R.string.grid_view));
+ gridRowAdapter.add(getString(R.string.error_fragment));
+ gridRowAdapter.add(getString(R.string.personal_settings));
+ mRowsAdapter.add(new ListRow(gridHeader, gridRowAdapter));
+
+ setAdapter(mRowsAdapter);
+
+ updateRecommendations();
+}
+</pre>
+
+<h2 id="card-view">Create a Card View</h2>
+
+<p>In this step, you build the card presenter with a view holder for the card view that describes
+your media content items. Note that each presenter must only create one view type. If you have two
+different card view types then you need two different card presenters.</p>
+
+<p>In the {@link android.support.v17.leanback.widget.Presenter}, implement an
+{@link android.support.v17.leanback.widget.Presenter#onCreateViewHolder(android.view.ViewGroup) onCreateViewHolder()}
+callback that creates a view holder that can be used to display a content item.</p>
+
+<pre>
+&#64;Override
+public class CardPresenter extends Presenter {
+
+ private Context mContext;
+ private static int CARD_WIDTH = 313;
+ private static int CARD_HEIGHT = 176;
+ private Drawable mDefaultCardImage;
+
+ &#64;Override
+ public ViewHolder onCreateViewHolder(ViewGroup parent) {
+ mContext = parent.getContext();
+ mDefaultCardImage = mContext.getResources().getDrawable(R.drawable.movie);
+...
+</pre>
+
+<p>In the {@link android.support.v17.leanback.widget.Presenter#onCreateViewHolder(android.view.ViewGroup)
+onCreateViewHolder()} method, create a card view for content items. The sample below uses an
+{@link android.support.v17.leanback.widget.ImageCardView}.</p>
+
+<p>When a card is selected, the default behavior expands it to a larger size. If you want to designate
+a different color for the selected card, call {@link android.support.v17.leanback.widget.BaseCardView#setSelected(boolean)
+setSelected()}
+as shown here.</p>
+
+<pre>
+...
+ ImageCardView cardView = new ImageCardView(mContext) {
+ &#64;Override
+ public void setSelected(boolean selected) {
+ int selected_background = mContext.getResources().getColor(R.color.detail_background);
+ int default_background = mContext.getResources().getColor(R.color.default_background);
+ int color = selected ? selected_background : default_background;
+ findViewById(R.id.info_field).setBackgroundColor(color);
+ super.setSelected(selected);
+ }
+ };
+...
+</pre>
+
+<p>When the user opens your app, the {@link android.support.v17.leanback.widget.Presenter.ViewHolder}
+displays the <code>CardView</code> objects for your content items. You need to set these to receive
+focus from the D-pad controller by calling {@link android.view.View#setFocusable(boolean) setFocusable(true)}
+and {@link android.view.View#setFocusableInTouchMode(boolean) setFocusableInTouchMode(true)}.</p>
+
+<pre>
+...
+ cardView.setFocusable(true);
+ cardView.setFocusableInTouchMode(true);
+ return new ViewHolder(cardView);
+}
+</pre>
+
+<p>When the user selects the {@link android.support.v17.leanback.widget.ImageCardView}, it expands
+to reveal its text area with the background color you specify, as shown in figure 2.</p>
+
+<img itemprop="image" src="{@docRoot}images/tv/card-view.png" alt="App card view"/>
+<p class="img-caption"><b>Figure 2.</b> The <a href="https://github.com/googlesamples/androidtv-Leanback">
+Leanback sample app</a> image card view when selected.</p>
+
+
diff --git a/docs/html/training/tv/playback/index.jd b/docs/html/training/tv/playback/index.jd
index 5427d48..0e9c5ec 100644
--- a/docs/html/training/tv/playback/index.jd
+++ b/docs/html/training/tv/playback/index.jd
@@ -56,6 +56,9 @@ startpage=true
<dd>Learn how to use the Leanback support library to build a browsing interface for media
catalogs.</dd>
+ <dt><b><a href="details.html">Providing a Card View</a></b></dt>
+ <dd>Learn how to use the Leanback support library to build a card view for content items.</dd>
+
<dt><b><a href="details.html">Building a Details View</a></b></dt>
<dd>Learn how to use the Leanback support library to build a details page for media items.</dd>
diff --git a/docs/html/training/tv/start/layouts.jd b/docs/html/training/tv/start/layouts.jd
index 177ea7a..a378096 100644
--- a/docs/html/training/tv/start/layouts.jd
+++ b/docs/html/training/tv/start/layouts.jd
@@ -119,8 +119,8 @@ trainingnavtop=true
<p>
Avoid screen elements being clipped due to overscan and by incorporating a 10% margin
- on all sides of your layout. This translates into a 27dp margin on the left and right edges and
- a 48dp margin on the top and bottom of your base layouts for activities. The following
+ on all sides of your layout. This translates into a 48dp margin on the left and right edges and
+ a 27dp margin on the top and bottom of your base layouts for activities. The following
example layout demonstrates how to set these margins in the root layout for a TV app:
</p>
diff --git a/docs/html/training/wearables/data-layer/data-items.jd b/docs/html/training/wearables/data-layer/data-items.jd
index 12babbf..49a8d32 100644
--- a/docs/html/training/wearables/data-layer/data-items.jd
+++ b/docs/html/training/wearables/data-layer/data-items.jd
@@ -46,7 +46,7 @@ directly. Instead, you:
</ol>
<p>
-However, instead of working with raw bytes using <a href="{@docRoot}reference/com/google/android/gms/wearable/PutDataRequest.html#setData(byte[])">setData()</a>,
+However, instead of working with raw bytes using <a href="{@docRoot}reference/com/google/android/gms/wearable/PutDataRequest.html#setData(byte[])"><code>setData()</code></a>,
we recommend you <a href="#SyncData">use a data map</a>, which exposes
a data item in an easy-to-use {@link android.os.Bundle}-like interface.
</p>
@@ -88,39 +88,121 @@ app, you should create a path scheme that matches the structure of the data.
</li>
</ol>
-<p>The following example shows how to create a data map and put data on it:</p>
+<p>The <code>increaseCounter()</code> method in the following example shows how to create a
+data map and put data in it:</p>
<pre>
-PutDataMapRequest dataMap = PutDataMapRequest.create("/count");
-dataMap.getDataMap().putInt(COUNT_KEY, count++);
-PutDataRequest request = dataMap.asPutDataRequest();
-PendingResult&lt;DataApi.DataItemResult&gt; pendingResult = Wearable.DataApi
- .putDataItem(mGoogleApiClient, request);
+public class MainActivity extends Activity implements
+ DataApi.DataListener,
+ GoogleApiClient.ConnectionCallbacks,
+ GoogleApiClient.OnConnectionFailedListener {
+
+ private static final String COUNT_KEY = "com.example.key.count";
+
+ private GoogleApiClient mGoogleApiClient;
+ private int count = 0;
+
+ ...
+
+ // Create a data map and put data in it
+ private void <strong>increaseCounter</strong>() {
+ PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/count");
+ putDataMapReq.getDataMap().putInt(COUNT_KEY, count++);
+ PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
+ PendingResult&lt;DataApi.DataItemResult> pendingResult =
+ Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
+ }
+
+ ...
+}
</pre>
+<p>For more information about handling the
+<a href="{@docRoot}reference/com/google/android/gms/common/api/PendingResult.html">
+<code>PendingResult</code></a> object, see
+<a href="{@docRoot}training/wearables/data-layer/events.html#Wait">Wait for the Status of Data
+Layer Calls</a>.</p>
+
+
<h2 id="ListenEvents">Listen for Data Item Events</h2>
-If one side of the data layer connection changes a data item, you probably want
+
+<p>If one side of the data layer connection changes a data item, you probably want
to be notified of any changes on the other side of the connection.
-You can do this by implementing a listener for data item events.
+You can do this by implementing a listener for data item events.</p>
-<p>For example, here's what a typical callback looks like to carry out certain actions
-when data changes:</p>
+<p>The code snippet in the following example notifies your app when the value of the
+counter defined in the previous example changes:</p>
<pre>
-&#64;Override
-public void onDataChanged(DataEventBuffer dataEvents) {
- for (DataEvent event : dataEvents) {
- if (event.getType() == DataEvent.TYPE_DELETED) {
- Log.d(TAG, "DataItem deleted: " + event.getDataItem().getUri());
- } else if (event.getType() == DataEvent.TYPE_CHANGED) {
- Log.d(TAG, "DataItem changed: " + event.getDataItem().getUri());
+public class MainActivity extends Activity implements
+ DataApi.DataListener,
+ GoogleApiClient.ConnectionCallbacks,
+ GoogleApiClient.OnConnectionFailedListener {
+
+ private static final String COUNT_KEY = "com.example.key.count";
+
+ private GoogleApiClient mGoogleApiClient;
+ private int count = 0;
+
+ &#64;Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ &#64;Override
+ protected void onResume() {
+ super.onStart();
+ mGoogleApiClient.connect();
+ }
+
+ &#64;Override
+ public void onConnected(Bundle bundle) {
+ <strong>Wearable.DataApi.addListener</strong>(mGoogleApiClient, this);
+ }
+
+ &#64;Override
+ protected void onPause() {
+ super.onPause();
+ <strong>Wearable.DataApi.removeListener</strong>(mGoogleApiClient, this);
+ mGoogleApiClient.disconnect();
+ }
+
+ &#64;Override
+ public void <strong>onDataChanged</strong>(DataEventBuffer dataEvents) {
+ for (DataEvent event : dataEvents) {
+ if (event.getType() == DataEvent.TYPE_CHANGED) {
+ // DataItem changed
+ DataItem item = event.getDataItem();
+ if (item.getUri().getPath().compareTo("/count") == 0) {
+ DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
+ updateCount(dataMap.getInt(COUNT_KEY));
+ }
+ } else if (event.getType() == DataEvent.TYPE_DELETED) {
+ // DataItem deleted
+ }
}
}
+
+ // Our method to update the count
+ private void updateCount(int c) { ... }
+
+ ...
}
</pre>
-<p>
-This is just a snippet that requires more implementation details. Learn about
-how to implement a full listener service or activity in
+
+<p>This activity implements the
+<a href="{@docRoot}reference/com/google/android/gms/wearable/DataApi.DataListener.html">
+<code>DataItem.DataListener</code></a> interface. This activity adds itself as a listener
+for data item events inside the <code>onConnected()</code> method and removes the listener
+in the <code>onPause()</code> method.</p>
+
+<p>You can also implement the listener as a service. For more information, see
<a href="{@docRoot}training/wearables/data-layer/events.html#Listen">Listen for Data Layer
-Events</a>.
-</p> \ No newline at end of file
+Events</a>.</p>
diff --git a/docs/html/training/wearables/data-layer/events.jd b/docs/html/training/wearables/data-layer/events.jd
index 6a3949a..c797f68 100644
--- a/docs/html/training/wearables/data-layer/events.jd
+++ b/docs/html/training/wearables/data-layer/events.jd
@@ -267,6 +267,8 @@ or <a href="{@docRoot}reference/com/google/android/gms/wearable/NodeApi.html#rem
public class MainActivity extends Activity implements
DataApi.DataListener, ConnectionCallbacks, OnConnectionFailedListener {
+ private GoogleApiClient mGoogleApiClient;
+
&#64;Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -314,4 +316,5 @@ public class MainActivity extends Activity implements
}
}
}
+}
</pre>
diff --git a/docs/html/training/wearables/data-layer/messages.jd b/docs/html/training/wearables/data-layer/messages.jd
index 822e395..0ca55ba 100644
--- a/docs/html/training/wearables/data-layer/messages.jd
+++ b/docs/html/training/wearables/data-layer/messages.jd
@@ -39,16 +39,24 @@ to Google Play services and when to use each in
</p>
<pre>
-Node node; // the connected device to send the message to
GoogleApiClient mGoogleApiClient;
-public static final START_ACTIVITY_PATH = "/start/MainActivity";
+public static final String START_ACTIVITY_PATH = "/start/MainActivity";
...
- SendMessageResult result = Wearable.MessageApi.sendMessage(
- mGoogleApiClient, node, START_ACTIVITY_PATH, null).await();
- if (!result.getStatus().isSuccess()) {
- Log.e(TAG, "ERROR: failed to send Message: " + result.getStatus());
- }
+private void sendStartActivityMessage(String nodeId) {
+ Wearable.MessageApi.sendMessage(
+ mGoogleApiClient, nodeId, START_ACTIVITY_PATH, new byte[0]).setResultCallback(
+ new ResultCallback&lt;SendMessageResult>() {
+ &#64;Override
+ public void onResult(SendMessageResult sendMessageResult) {
+ if (!sendMessageResult.getStatus().isSuccess()) {
+ Log.e(TAG, "Failed to send message with status code: "
+ + sendMessageResult.getStatus().getStatusCode());
+ }
+ }
+ }
+ );
+}
</pre>
<p>
diff --git a/docs/html/training/wearables/watch-faces/configuration.jd b/docs/html/training/wearables/watch-faces/configuration.jd
index edc7eac..5a4585d 100644
--- a/docs/html/training/wearables/watch-faces/configuration.jd
+++ b/docs/html/training/wearables/watch-faces/configuration.jd
@@ -92,7 +92,7 @@ and declare the following intent filter in the manifest file of the wearable app
&lt;action android:name=
"com.example.android.wearable.watchface.CONFIG_DIGITAL" />
&lt;category android:name=
- "com.google.android.wearable.watchface.category.WEARABLE_CONFIGURATION" />
+ <strong>"com.google.android.wearable.watchface.category.WEARABLE_CONFIGURATION"</strong> />
&lt;category android:name="android.intent.category.DEFAULT" />
&lt;/intent-filter>
&lt;/activity>
@@ -119,8 +119,21 @@ a handheld device. For example, a configuration activity on a handheld device en
present users with elaborate color pickers to select the background color of a watch face.</p>
<p>To create a companion configuration activity, add a new activity to your handheld app module and
-declare the same intent filter for this activity as the one in <a href="#WearableActivity">Create
-a Wearable Configuration Activity</a>.</p>
+declare the following intent filter in the manifest file of the handheld app:</p>
+
+<pre>
+&lt;activity
+ android:name=".DigitalWatchFaceCompanionConfigActivity"
+ android:label="@string/app_name">
+ &lt;intent-filter>
+ &lt;action android:name=
+ "com.example.android.wearable.watchface.CONFIG_DIGITAL" />
+ &lt;category android:name=
+ <strong>"com.google.android.wearable.watchface.category.COMPANION_CONFIGURATION"</strong> />
+ &lt;category android:name="android.intent.category.DEFAULT" />
+ &lt;/intent-filter>
+&lt;/activity>
+</pre>
<p>In your configuration activity, build a UI that provides options to customize all the
configurable elements of your watch face. When users make a selection, use the <a
diff --git a/docs/html/training/wearables/watch-faces/drawing.jd b/docs/html/training/wearables/watch-faces/drawing.jd
index 9afdd80..3c5da34 100644
--- a/docs/html/training/wearables/watch-faces/drawing.jd
+++ b/docs/html/training/wearables/watch-faces/drawing.jd
@@ -192,13 +192,14 @@ as described in <a href="#Drawing">Drawing Your Watch Face</a>.</p>
<h3 id="Timer">Initialize the custom timer</h3>
-<p>As a watch face developer, you can decide how often you want to update your watch face by
+<p>As a watch face developer, you decide how often you want to update your watch face by
providing a custom timer that ticks with the required frequency while the device is in
-interactive mode. This enables you to create custom animations and other visual effects. In
-ambient mode, you should disable the timer to let the CPU sleep and update the watch face
-only when the time changes. For more information, see
-<a href="{@docRoot}training/wearables/watch-faces/performance.html">Optimizing Performance and
-Battery Life</a>.</p>
+interactive mode. This enables you to create custom animations and other visual effects.
+</p>
+
+<p class="note"><strong>Note:</strong> In ambient mode, the system does not reliably call the
+custom timer. To update the watch face in ambient mode, see <a href="#TimeTick">Update the watch
+face in ambient mode</a>.</p>
<p>An example timer definition from the <code>AnalogWatchFaceService</code> class that ticks once
every second is shown in <a href="#Variables">Declare variables</a>. In the
@@ -210,9 +211,8 @@ conditions apply:</p>
<li>The device is in interactive mode.</li>
</ul>
-<p>The timer should not run under any other conditions, since this watch face does not
-draw the second hand in ambient mode to conserve power. The <code>AnalogWatchFaceService</code>
-class schedules the next timer tick if required as follows:</p>
+<p>The <code>AnalogWatchFaceService</code> class schedules the next timer tick if required as
+follows:</p>
<pre>
private void updateTimer() {
@@ -281,15 +281,15 @@ private void unregisterReceiver() {
-<h3 id="TimeTick">Invalidate the canvas when the time changes</h3>
+<h3 id="TimeTick">Update the watch face in ambient mode</h3>
-<p>The system calls the <code>Engine.onTimeTick()</code> method every minute. In ambient mode,
-it is usually sufficient to update your watch face once per minute. To update your watch face
-more often while in interactive mode, you provide a custom timer as described in
+<p>In ambient mode, the system calls the <code>Engine.onTimeTick()</code> method every minute.
+It is usually sufficient to update your watch face once per minute in this mode. To update your
+watch face while in interactive mode, you must provide a custom timer as described in
<a href="#Timer">Initialize the custom timer</a>.</p>
-<p>Most watch face implementations just invalidate the canvas to redraw the watch face when
-the time changes:</p>
+<p>In ambient mode, most watch face implementations simply invalidate the canvas to redraw the watch
+face in the <code>Engine.onTimeTick()</code> method:</p>
<pre>
&#64;Override
@@ -402,20 +402,17 @@ method for the system to redraw the watch face.</p>
&#64;Override
public void onAmbientModeChanged(boolean inAmbientMode) {
- boolean wasInAmbientMode = isInAmbientMode();
super.onAmbientModeChanged(inAmbientMode);
- if (inAmbientMode != wasInAmbientMode) {
- if (mLowBitAmbient) {
- boolean antiAlias = !inAmbientMode;
- mHourPaint.setAntiAlias(antiAlias);
- mMinutePaint.setAntiAlias(antiAlias);
- mSecondPaint.setAntiAlias(antiAlias);
- mTickPaint.setAntiAlias(antiAlias);
- }
- invalidate();
- updateTimer();
+ if (mLowBitAmbient) {
+ boolean antiAlias = !inAmbientMode;
+ mHourPaint.setAntiAlias(antiAlias);
+ mMinutePaint.setAntiAlias(antiAlias);
+ mSecondPaint.setAntiAlias(antiAlias);
+ mTickPaint.setAntiAlias(antiAlias);
}
+ invalidate();
+ updateTimer();
}
</pre>
@@ -478,7 +475,7 @@ public void onDraw(Canvas canvas, Rect bounds) {
float hrLength = centerX - 80;
// Only draw the second hand in interactive mode.
- if (!mAmbient) {
+ if (!isInAmbientMode()) {
float secX = (float) Math.sin(secRot) * secLength;
float secY = (float) -Math.cos(secRot) * secLength;
canvas.drawLine(centerX, centerY, centerX + secX, centerY +
diff --git a/docs/html/training/wearables/watch-faces/index.jd b/docs/html/training/wearables/watch-faces/index.jd
index c7affd1..453c30e 100644
--- a/docs/html/training/wearables/watch-faces/index.jd
+++ b/docs/html/training/wearables/watch-faces/index.jd
@@ -21,6 +21,14 @@ page.title=Creating Watch Faces
</div>
</a>
+<a class="notice-developers-video wide"
+ href="https://www.youtube.com/watch?v=AK38PJZmIW8">
+<div>
+ <h3>Video</h3>
+ <p>DevBytes: Watch Faces for Android Wear</p>
+</div>
+</a>
+
<p>Watch faces in Android Wear leverage a dynamic digital canvas to tell time using colors,
animations, and relevant contextual information. The <a
href="https://play.google.com/store/apps/details?id=com.google.android.wearable.app">Android
diff --git a/docs/html/training/wearables/watch-faces/service.jd b/docs/html/training/wearables/watch-faces/service.jd
index 7ab575e..35366c5 100644
--- a/docs/html/training/wearables/watch-faces/service.jd
+++ b/docs/html/training/wearables/watch-faces/service.jd
@@ -64,42 +64,15 @@ Project</a>.</p>
<h3 id="Dependencies">Dependencies</h3>
-<p>For the handheld app, edit the <code>build.gradle</code> file in the <code>mobile</code> module
-to add these dependencies:</p>
-
-<pre>
-apply plugin: 'com.android.application'
-
-android { ... }
-
-dependencies {
- ...
- wearApp project(':wear')
- compile 'com.google.android.gms:play-services:6.5.+'
-}
-</pre>
-
-<p>For the wearable app, edit the <code>build.gradle</code> file in the <code>wear</code> module
-to add these dependencies:</p>
-
-<pre>
-apply plugin: 'com.android.application'
-
-android { ... }
-
-dependencies {
- ...
- compile 'com.google.android.support:wearable:1.1.+'
- compile 'com.google.android.gms:play-services-wearable:6.5.+'
-}
-</pre>
-
<p>The Wearable Support Library provides the necessary classes that you extend to create watch
face implementations. The Google Play services client libraries (<code>play-services</code> and
<code>play-services-wearable</code>) are required to sync data items between the companion device
and the wearable with the <a href="{@docRoot}training/wearables/data-layer/index.html">Wearable
Data Layer API</a>.</p>
+<p>Android Studio automatically adds the required entries in your <code>build.gradle</code>
+files when you create the project in the instructions above.</p>
+
<h3 id="Reference">Wearable Support Library API Reference</h3>
<p>The reference documentation provides detailed information about the classes you use to