diff options
86 files changed, 2494 insertions, 8672 deletions
diff --git a/docs/html-intl/intl/es/design/patterns/notifications.jd b/docs/html-intl/intl/es/design/patterns/notifications.jd deleted file mode 100644 index 5499e8b3d4e1..000000000000 --- a/docs/html-intl/intl/es/design/patterns/notifications.jd +++ /dev/null @@ -1,872 +0,0 @@ -page.title=Notificaciones -page.tags="notifications","design","L" -@jd:body - - <a class="notice-developers" href="{@docRoot}training/notify-user/index.html"> - <div> - <h3>Documentos para desarrolladores</h3> - <p>Cómo notificar al usuario</p> - </div> -</a> - -<a class="notice-designers" href="notifications_k.html"> - <div> - <h3>Notificaciones en Android 4.4 y versiones anteriores</h3> - </div> -</a> - -<!-- video box --> -<a class="notice-developers-video" href="https://www.youtube.com/watch?v=Uiq2kZ2JHVY"> -<div> - <h3>Video</h3> - <p>DevBytes: Notificaciones en la vista previa para desarrolladores de Android L</p> -</div> -</a> - -<style> - .col-5, .col-6, .col-7 { - margin-left:0px; - } -</style> - -<p>El sistema de notificaciones les permite a los usuarios mantenerse informados sobre eventos relevantes y -oportunos -de su aplicación, como nuevos mensajes de chat de un amigo o un evento del calendario. -Piense en las notificaciones como un canal de noticias que alerta a los usuarios sobre eventos -importantes -a medida que se producen o como un registro en el que se relatan los eventos mientras el usuario no está prestando -atención y que se sincroniza de forma correspondiente en todos los dispositivos de Android.</p> - -<h4 id="New"><strong>Novedades de Android 5.0</strong></h4> - -<p>En Android 5.0, las notificaciones reciben actualizaciones importantes a nivel estructural, -visual y funcional.</p> - -<ul> - <li>En las notificaciones, se han realizado cambios visuales de forma coherente con el nuevo -tema Material Design.</li> - <li> Las notificaciones ahora están disponibles en la pantalla de bloqueo del dispositivo y -el contenido confidencial se puede seguir - ocultando detrás de dicha pantalla.</li> - <li>En las notificaciones de alta prioridad que se reciben cuando el dispositivo está en uso, ahora se utiliza un nuevo formato llamado - notificaciones emergentes.</li> - <li>Notificaciones sincronizadas en la nube: Si se omite una notificación en un dispositivo -Android, esta se omitirá - también en los demás dispositivos.</li> -</ul> - -<p class="note"><strong>Nota:</strong> El diseño de las notificaciones de esta versión de -Android se diferencia -de manera significativa del diseño de las versiones anteriores. Para obtener información sobre el diseño de las notificaciones en versiones -anteriores, consulte <a href="./notifications_k.html">Notificaciones en Android 4.4 y versiones anteriores</a>.</p> - -<h2 id="Anatomy">Anatomía de una notificación</h2> - -<p>En esta sección, se repasan las partes básicas de una notificación y cómo se pueden mostrar en -diferentes tipos de dispositivos.</p> - -<h3 id="BaseLayout">Diseño básico</h3> - -<p>Como mínimo, todas las notificaciones poseen un diseño básico que incluye lo siguiente:</p> - -<ul> - <li> El <strong>icono</strong> de la notificación. El icono simboliza la -aplicación que lo origina. También puede - indicar el tipo de notificación si la aplicación genera más de un -tipo.</li> - <li> <strong>Título</strong> de la notificación y -<strong>texto</strong> adicional.</li> - <li> Una <strong>marca de tiempo</strong>.</li> -</ul> - -<p>Las notificaciones creadas con {@link android.app.Notification.Builder Notification.Builder} -para versiones anteriores de la plataforma lucen y funcionan igual en Android -5.0; solo presentan algunos cambios de estilo que el sistema realiza -por usted. Para obtener más información sobre las notificaciones en versiones anteriores de -Android, consulte -<a href="./notifications_k.html">Notificaciones en Android 4.4 y versiones anteriores</a>.</p></p> - - - <img style="margin:20px 0 0 0" src="{@docRoot}images/android-5.0/notifications/basic_combo.png" alt="" width="700px" /> - - -<div style="clear:both;margin-top:20px"> - <p class="img-caption"> - Diseño básico de una notificación para dispositivos portátiles (izquierda) y la misma notificación en Wear (derecha), - con una fotografía del usuario y un icono de la notificación - </p> - </div> - -<h3 id="ExpandedLayouts">Diseños expandidos</h3> - - -<p>Usted puede decidir cuántos detalles mostrarán las notificaciones -de su aplicación. Las notificaciones pueden mostrar las primeras -líneas de un mensaje o la vista previa de una imagen más grande. A través de la -información adicional, se proporciona más -contexto al usuario y, en algunos casos, se puede permitir que el usuario lea todo el -mensaje. El usuario -puede acercar o alejar la imagen, o deslizar la imagen con un solo dedo para alternar entre los diseños compacto -y expandido. - En el caso de las notificaciones de un solo evento, Android proporciona tres plantillas de -diseños expandidos (texto, bandeja de entrada e - imagen) para que usted utilice en su aplicación. En las siguientes imágenes, se muestra cómo -se ven las notificaciones de un solo evento en los - dispositivos portátiles (izquierda) y los dispositivos con Wear (derecha).</p> - -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/expandedtext_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/stack_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/ExpandedImage.png" - alt="" width="311px" height;="450px" /> - -<h3 id="actions" style="clear:both; margin-top:40px">Acciones</h3> - -<p>Android es compatible con acciones opcionales que se muestran en la parte inferior -de la notificación. -A través de las acciones, los usuarios pueden administrar las tareas más comunes para una determinada -notificación desde el interior del panel de notificaciones, sin tener que abrir la -aplicación que la originó. -Esto acelera la interacción y, junto con la función deslizar para descartar, ayuda a los usuarios a enfocarse en las -notificaciones que les parecen importantes.</p> - - - <img src="{@docRoot}images/android-5.0/notifications/action_combo.png" alt="" width="700px" /> - - - -<p style="clear:both">Sea moderado con la cantidad de acciones que incluye en una -notificación. Mientras más -acciones incluya, mayor complejidad cognitiva generará. Limítese a -la menor cantidad posible -de acciones al incluir solo las acciones más importantes -y significativas.</p> - -<p>Las acciones recomendadas para las notificaciones son aquellas que:</p> - -<ul> - <li> Son fundamentales, frecuentes y típicas para el tipo de contenido que está -mostrando. - <li> Les permiten a los usuarios realizar las tareas rápidamente. -</ul> - -<p>Evite acciones que sean:</p> - -<ul> - <li> ambiguas; - <li> iguales que la acción predeterminada de la notificación (tales como "Leer" o -"Abrir"). -</ul> - - - -<p>Puede especificar un máximo de tres acciones, cada una de ellas formada por un icono -de la acción y un nombre. - Al agregarle acciones a un diseño básico simple, la notificación será expandible, -incluso si no - cuenta con un diseño expandido. Como las acciones solo se muestran en las notificaciones -expandidas - y, de lo contrario, se ocultan, asegúrese de que cualquier acción que el -usuario invoque desde - una notificación esté disponible también desde la aplicación -asociada.</p> - -<h2 style="clear:left">Notificación emergente</h2> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/hun-example.png" alt="" width="311px" /> - <p class="img-caption"> - Ejemplo de una notificación emergente (llamada telefónica entrante, alta prioridad) -que aparece en la parte superior de una - aplicación inmersiva - </p> -</div> - -<p>Cuando llega una notificación de alta prioridad (ver a la derecha), esta se presenta -a los usuarios -durante un período breve, con un diseño expandido que expone las posibles acciones.</p> -<p> Luego de este período, la notificación se retira hacia el -panel de notificaciones. Si la <a href="#correctly_set_and_manage_notification_priority">prioridad</a> de una notificación -se marca como Alta, Máxima o Pantalla completa, se obtiene una notificación emergente.</p> - -<p><b>Buenos ejemplos de notificaciones emergentes</b></p> - -<ul> - <li> Llamada telefónica entrante cuando se utiliza un dispositivo</li> - <li> Alarma cuando se utiliza un dispositivo</li> - <li> Nuevo mensaje SMS</li> - <li> Batería baja</li> -</ul> - -<h2 style="clear:both" id="guidelines">Pautas</h2> - - -<h3 id="MakeItPersonal">Personalización</h3> - -<p>En el caso de las notificaciones de los elementos que envía otra persona (como un mensaje o una -actualización de estado), utilice -{@link android.app.Notification.Builder#setLargeIcon setLargeIcon()} para incluir la imagen de esa persona. Además, adjunte información sobre -la persona en los metadatos de la notificación (consulte {@link android.app.Notification#EXTRA_PEOPLE}).</p> - -<p>El icono principal de su notificación seguirá estando visible, de modo que el usuario pueda asociarlo -con el icono -que se muestra en la barra de estado.</p> - - -<img src="{@docRoot}images/android-5.0/notifications/Triggered.png" alt="" width="311px" /> -<p style="margin-top:10px" class="img-caption"> - Notificación en la que se muestra la persona que la generó y el contenido que envió. -</p> - - -<h3 id="navigate_to_the_right_place">Navegación hacia el lugar correcto</h3> - -<p>Cuando el usuario toca el cuerpo de una notificación (fuera de los botones de acción -), esta se abre -en el lugar en el que el usuario puede visualizarla y utilizar los datos que se mencionan en la -notificación. En la mayoría de los casos, se tratará de la vista detallada de un solo elemento de datos como un mensaje, -pero también se podría tratar de una -vista resumida si la notificación está apilada. Si la aplicación dirige al -usuario a cualquier sitio que se encuentre debajo del nivel superior, incorpore la navegación en la pila de retroceso de la aplicación para que el -usuario pueda presionar el botón Back del sistema y regresar al nivel superior. Para obtener más información, consulte -<em>Navegación dentro de la aplicación a través de los widgets y las notificaciones de la pantalla de Inicio</em> en el patrón de -diseño <a href="{@docRoot}design/patterns/navigation.html#into-your-app">Navegación</a>.</p> - -<h3 id="correctly_set_and_manage_notification_priority">Configuración y administración -correctas de la prioridad -de las notificaciones</h3> - -<p>Android admite el uso de una marca de prioridad en las notificaciones. Esta marca -le permite influir en el lugar donde aparecerá la notificación, en relación con otras notificaciones, y -lo ayuda a asegurarse de -que los usuarios vean siempre primero las notificaciones más importantes. Cuando publica una notificación, puede elegir -entre los -siguientes niveles de prioridad:</p> -<table> - <tr> - <td class="tab0"> -<p><strong>Prioridad</strong></p> -</td> - <td class="tab0"> -<p><strong>Uso</strong></p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MAX</code></p> -</td> - <td class="tab1"> -<p>Utilícelo para las notificaciones críticas y urgentes en las que se le informa al usuario sobre una condición -que es -crítica en el tiempo o que se debe resolver antes de que el usuario continúe con una -tarea específica.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>HIGH</code></p> -</td> - <td class="tab1"> -<p>Utilícelo, principalmente, para comunicaciones importantes, como eventos de mensajes o -chats con contenido que sea particularmente interesante para el usuario. -Las notificaciones de alta prioridad activan la pantalla de notificaciones emergentes.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>DEFAULT</code></p> -</td> - <td class="tab1"> -<p>Utilícelo para todas las notificaciones que no pertenecen a ninguno de los otros tipos de prioridades que se describen aquí.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>LOW</code></p> -</td> - <td class="tab1"> -<p>Utilícelo para las notificaciones que desea que el usuario reciba, pero -que son menos urgentes. Las notificaciones de baja prioridad tienden a aparecer en la parte inferior de la lista, -por lo que son ideales para -eventos como actualizaciones sociales públicas o indirectas: El usuario solicitó que se le notifiquen -estas -actualizaciones, pero estas notificaciones nunca tendrán prioridad sobre las comunicaciones -urgentes o directas.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MIN</code></p> -</td> - <td class="tab1"> -<p>Utilícelo para la información contextual o de segundo plano, como información sobre el clima o la -ubicación contextual. -Las notificaciones cuya prioridad es mínima no aparecen en la barra de estado. El usuario -las descubre al expandir el panel de notificaciones.</p> -</td> - </tr> -</table> - - -<h4 id="how_to_choose_an_appropriate_priority"><strong>Cómo elegir la -prioridad -adecuada</strong></h4> - -<p><code>DEFAULT</code>, <code>HIGH</code> y <code>MAX</code> son niveles de prioridad interruptiva, y se corre el riesgo de -interrumpir al usuario -en el medio de su actividad. Para evitar incomodar a los usuarios de su aplicación, reserve los niveles de prioridad interruptiva para -las notificaciones:</p> - -<ul> - <li> en las que participe otra persona;</li> - <li> en las que el tiempo sea importante;</li> - <li> que puedan modificar inmediatamente el comportamiento del usuario en el mundo real.</li> -</ul> - -<p>Las notificaciones que se configuran en <code>LOW</code> y <code>MIN</code> pueden seguir siendo -valiosas para el usuario: muchas, tal vez la mayoría, de las notificaciones simplemente no le piden al usuario que actúe de inmediato -ni llaman su atención mediante una vibración, pero poseen información que será valiosa para el -usuario -cuando este decida ver las notificaciones. Entre los criterios de las notificaciones con prioridad <code>LOW</code> y <code>MIN</code>, -se incluyen los siguientes:</p> - -<ul> - <li> No participan otras personas.</li> - <li> El tiempo no es importante.</li> - <li> Incluyen contenido que podría interesarle al usuario, pero que tal vez desee -buscarlo cuando lo necesite.</li> -</ul> - - - <img src="{@docRoot}images/android-5.0/notifications/notifications_pattern_priority.png" alt="" width="700" /> - - -<h3 style="clear:both" id="set_a_notification_category">Configuración de una -categoría de notificaciones</h3> - -<p>Si su notificación se puede clasificar dentro de alguna de las categorías predefinidas (consulte -a continuación), asígnela -según corresponda. Esta información se puede utilizar en determinados aspectos de la IU del sistema, como el panel de notificaciones (o cualquier -otro -agente de escucha de la notificación), para realizar una clasificación y filtrar las decisiones.</p> -<table> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_CALL">CATEGORY_CALL</a></code></p> -</td> - <td> -<p>Llamada entrante (voz o video) o una solicitud de comunicación -sincrónica similar</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_MESSAGE">CATEGORY_MESSAGE</a></code></p> -</td> - <td> -<p>Mensaje entrante directo (SMS, mensaje instantáneo, etc.)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EMAIL">CATEGORY_EMAIL</a></code></p> -</td> - <td> -<p>Mensaje en bloque asíncrono (correo electrónico)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EVENT">CATEGORY_EVENT</a></code></p> -</td> - <td> -<p>Evento del calendario</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROMO">CATEGORY_PROMO</a></code></p> -</td> - <td> -<p>Promoción o anuncio</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ALARM">CATEGORY_ALARM</a></code></p> -</td> - <td> -<p>Alarma o temporizador</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROGRESS">CATEGORY_PROGRESS</a></code></p> -</td> - <td> -<p>Progreso de una operación en segundo plano de larga ejecución</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SOCIAL">CATEGORY_SOCIAL</a></code></p> -</td> - <td> -<p>Actualización de red social o uso compartido de datos</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ERROR">CATEGORY_ERROR</a></code></p> -</td> - <td> -<p>Error en una operación en segundo plano o un estado de autenticación</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_TRANSPORT">CATEGORY_TRANSPORT</a></code></p> -</td> - <td> -<p>Control de transporte de medios para la reproducción</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SYSTEM">CATEGORY_SYSTEM</a></code></p> -</td> - <td> -<p>Actualización del estado del dispositivo o el sistema. Reservado para ser utilizado por el sistema</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SERVICE">CATEGORY_SERVICE</a></code></p> -</td> - <td> -<p>Indicación de ejecución de servicio en segundo plano</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_RECOMMENDATION">CATEGORY_RECOMMENDATION</a></code></p> -</td> - <td> -<p>Una recomendación específica y oportuna para un solo evento. Por ejemplo, en una -aplicación de noticias tal vez se desee -recomendar una historia que se considere que el usuario deseará leer luego</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_STATUS">CATEGORY_STATUS</a></code></p> -</td> - <td> -<p>Información constante sobre el estado contextual o del dispositivo</p> -</td> - </tr> -</table> - -<h3 id="summarize_your_notifications">Resumen de las notificaciones</h3> - -<p>Si una notificación de un determinado tipo ya está pendiente cuando su aplicación intenta enviar una nueva -notificación del mismo tipo, combínelas en una misma notificación resumida para la aplicación. No -cree un objeto nuevo.</p> - -<p>Las notificaciones resumidas incluirán una descripción resumida y le permitirán al usuario -conocer cuántas -notificaciones de un determinado tipo están pendientes.</p> - -<div class="col-6"> - -<p><strong>Lo que no debe hacer</strong></p> - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Dont.png" alt="" width="311px" /> -</div> - -<div> -<p><strong>Lo que debe hacer</strong></p> - - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Do.png" alt="" width="311px" /> -</div> - -<p style="clear:left; padding-top:30px; padding-bottom:20px">Puede proporcionar -información más detallada sobre cada una de las notificaciones que conforman un - resumen al utilizar el diseño resumido expandido. Este enfoque les permite a los usuarios tener -una idea más clara de las - notificaciones pendientes y determinar si están lo suficientemente interesados como para leer -los detalles en la - aplicación asociada.</p> -<div class="col-6"> - <img src="{@docRoot}images/android-5.0/notifications/Stack.png" style="margin-bottom:20px" alt="" width="311px" /> - <p class="img-caption"> - Notificación contraída y expandida que es un resumen (mediante el uso de <code>InboxStyle</code>) - </p> -</div> - -<h3 style="clear:both" id="make_notifications_optional">Uso de notificaciones -opcionales</h3> - -<p>Los usuarios deben tener siempre el control sobre las notificaciones. Permítale al usuario -deshabilitar las notificaciones -de su aplicación o cambiar las propiedades de las alertas, como el sonido de una alerta y si desea -utilizar la vibración, -mediante la incorporación de un elemento de configuración de notificaciones en las configuraciones de la aplicación.</p> - -<h3 id="use_distinct_icons">Uso de iconos diferentes</h3> -<p>Al mirar el área de notificaciones, el usuario debe poder diferenciar -los tipos de -notificaciones que están pendientes actualmente.</p> - -<div class="figure"> - <img src="{@docRoot}images/android-5.0/notifications/ProductIcons.png" alt="" width="420" /> -</div> - - <div><p><strong>Lo que debe hacer</strong></p> - <p>Mirar los iconos de notificaciones que ya se proporcionan en las aplicaciones de Android y crear -iconos de notificaciones para - su aplicación que tengan una apariencia bastante diferente.</p> - - <p><strong>Lo que debe hacer</strong></p> - <p>Utilizar el <a href="/design/style/iconography.html#notification">estilo de icono de notificación</a> - adecuado para los iconos pequeños y el -<a href="/design/style/iconography.html#action-bar">estilo -de icono de barra de acción</a> del diseño Material Light para los iconos - de acciones.</p> -<p ><strong>Lo que debe hacer</strong></p> -<p >Hacer que los iconos sean simples y evitar incluir una cantidad excesiva de detalles difíciles de -distinguir.</p> - - <div><p><strong>Lo que no debe hacer</strong></p> - <p>Colocar valores alfa adicionales (que se oscurezcan o aclaren) en los -iconos pequeños y los - iconos de acciones. Estos pueden tener bordes alisados, pero como en Android estos iconos se utilizan -como máscaras (es decir, solo se - utiliza el canal alfa), por lo general, la imagen se debe dibujar con -opacidad completa.</p> - -</div> -<p style="clear:both"><strong>Lo que no debe hacer</strong></p> - -<p>Utilizar colores para diferenciar su aplicación de las demás. Los iconos de las notificaciones simplemente -deben ser una imagen sobre un fondo blanco o transparente.</p> - - -<h3 id="pulse_the_notification_led_appropriately">Pulsación adecuada del -LED de notificaciones</h3> - -<p>Muchos dispositivos con Android incluyen un LED de notificaciones, que se utiliza para mantener al -usuario informado sobre los -eventos cuando la pantalla está apagada. Las notificaciones con un nivel de prioridad <code>MAX</code>, -<code>HIGH</code> o <code>DEFAULT</code> deben -hacer que se encienda el LED, mientras que las de menor prioridad (<code>LOW</code> y -<code>MIN</code>) no deben activar esta función.</p> - -<p>El control del usuario sobre las notificaciones debe extenderse al LED. Cuando se utilice -DEFAULT_LIGHTS, el -LED se iluminará en color blanco. Sus notificaciones no deberían utilizar un color -diferente, a menos que el -usuario lo haya personalizado explícitamente.</p> - -<h2 id="building_notifications_that_users_care_about">Creación de notificaciones -importantes para los usuarios</h2> - -<p>Para crear una aplicación que les guste a los usuarios, es importante diseñar las notificaciones -cuidadosamente. -Las notificaciones son la voz de su aplicación y ayudan a definir su -personalidad. Las notificaciones no deseadas -o que no son importantes pueden hacer que el usuario se moleste o no se sienta cómodo con la cantidad de -atención que le demanda la -aplicación, por eso debe utilizarlas de forma moderada.</p> - -<h3 id="when_to_display_a_notification">Cuándo se deben mostrar las notificaciones</h3> - -<p>Para crear una aplicación que los usuarios disfruten, es importante -reconocer que la atención -y el enfoque del usuario son recursos que se deben proteger. Aunque el sistema de notificaciones de Android -se diseñó -para minimizar el impacto de las notificaciones en la atención del usuario, -es -importante tener en cuenta que las notificaciones interrumpen el -flujo de tareas del usuario. -Cuando planifique sus notificaciones, pregúntese si son lo suficiente importantes como para -realizar una interrupción. Si no está seguro, permítale al usuario que elija las -notificaciones mediante la configuración de notificaciones de su aplicación o que ajuste -la marca de prioridad de las notificaciones en <code>LOW</code> o <code>MIN</code> para -evitar distraer al usuario cuando realiza -alguna otra tarea.</p> - - <img src="{@docRoot}images/android-5.0/notifications/TimeSensitive.png" alt="" width="311px" /> - <p style="margin-top:10px" class="img-caption"> - Ejemplos de notificaciones sujetas a limitación temporal - </p> - -<p>Aunque las aplicaciones más eficientes para el usuario solo proporcionan una respuesta cuando se la solicita, en algunos casos, -vale la pena que una aplicación interrumpa al usuario con una notificación no solicitada.</p> - -<p>Utilice las notificaciones principalmente para <strong>eventos sujetos a limitaciones temporales</strong>, en especial - si estos eventos sincrónicos <strong>involucran a otras personas</strong>. Por -ejemplo, un chat entrante - es una forma de comunicación sincrónica y en tiempo real: otro usuario -está esperando de forma activa su respuesta. Los eventos del calendario son otros buenos ejemplos de cuándo se debe utilizar una -notificación y llamar la atención del usuario, - ya que los eventos son inminentes y, generalmente, -involucran a otras personas.</p> - -<h3 style="clear:both" id="when_not_to_display_a_notification">Cuándo no se debe -mostrar una notificación</h3> - -<div class="figure" style="margin-top:60px"> - <img src="{@docRoot}images/android-5.0/notifications/AntiSample1.png" alt="" width="311px" /> -</div> - -<p>En muchos otros casos, no es apropiado enviar notificaciones:</p> - -<ul> - <li> Evite notificarle al usuario acerca de información que no le enviaron -específicamente a él o -información que no está verdaderamente sujeta a una limitación temporal. Por ejemplo, las actualizaciones asíncronas -e indirectas - que circulan por las redes sociales generalmente no justifican una interrupción en -tiempo real. En el caso de los usuarios - interesados en dichas notificaciones, permítales elegir.</li> - <li> No cree una notificación si la información nueva y relevante se muestra actualmente -en la pantalla. En su lugar, - utilice la IU de la aplicación para notificarle al usuario sobre la nueva información -directamente en contexto. - Por ejemplo, una aplicación de chat no debe crear notificaciones del sistema mientras -el usuario está chateando de forma activa con otro usuario.</li> - <li> No interrumpa al usuario para que ejecute operaciones técnicas de bajo nivel, como guardar -o sincronizar información, o actualizar una aplicación si dicha aplicación o el sistema pueden resolver el problema -sin la participación del usuario.</li> - <li> No interrumpa al usuario para informarle sobre un error si la -aplicación puede solucionar el error por sus propios medios, sin que el usuario -realice ninguna acción.</li> - <li> No cree notificaciones que no incluyan contenidos reales de notificación y que -simplemente promocionen - su aplicación. Una notificación debe proporcionar información nueva, útil y oportuna, y -no debe utilizarse - solo para lanzar una aplicación.</li> - <li> No cree notificaciones superfluas solo para mostrar su marca -a los usuarios. - Dichas notificaciones frustran y aíslan a su público. La -mejor forma de proporcionar - pequeñas cantidades de información actualizada y de mantener a los usuarios interesados -en su - aplicación es desarrollar un widget que puedan colocar en la -pantalla de inicio, si así lo desean.</li> -</ul> - -<h2 style="clear:left" id="interacting_with_notifications">Interacción con -las notificaciones</h2> - -<p>Las notificaciones se indican mediante iconos en la barra de estado, y se puede acceder a ellas -al abrir el -panel lateral de notificaciones.</p> - -<p>Al tocar una notificación, se abre la aplicación asociada con el contenido detallado -que coincide con el de la notificación. -Si dicha notificación se desplaza hacia la izquierda o la derecha, esta se eliminará del panel lateral.</p> - -<h3 id="ongoing_notifications">Notificaciones constantes</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/MusicPlayback.png" alt="" width="311px" /> - <p class="img-caption"> - Notificaciones constantes relacionadas con la reproducción de música - </p> -</div> -<p>Mediante las notificaciones constantes, se mantiene a los usuarios informados sobre un proceso en curso en -segundo plano. -Por ejemplo, los reproductores de música anuncian la pista que se está reproduciendo actualmente en el -sistema de notificaciones y -siguen haciéndolo hasta que el usuario detiene la reproducción. Mediante las notificaciones constantes también se le pueden -mostrar al usuario -comentarios sobre tareas más extensas, como descargar un archivo o codificar un video. Los usuarios no podrán -eliminar las notificaciones constantes del panel lateral de notificaciones.</p> - -<h3 id="ongoing_notifications">Reproducción de medios</h3> -<p>En Android 5.0, la pantalla de bloqueo no muestra los controles de transporte para la clase -{@link android.media.RemoteControlClient} obsoleta. Sin embargo, <em>sí</em> muestra las notificaciones, de modo que las notificaciones de reproducción de cada -aplicación ahora son la forma principal -en la que los usuarios controlan la reproducción desde el estado bloqueado. A través de este comportamiento, se le otorga más control -a la aplicación sobre los -botones que se deben mostrar, y la forma en que debe mostrarlos, al mismo tiempo que se proporciona -al usuario una experiencia coherente, independientemente de si la pantalla está bloqueada o no.</p> - -<h3 style="clear:both" -id="dialogs_and_toasts_are_for_feedback_not_notification">Diálogos -y avisos</h3> - -<p>Su aplicación no debe crear un diálogo o un aviso si actualmente no se muestra en la -pantalla. Los diálogos o los avisos se deben - mostrar únicamente como una respuesta inmediata a una acción que realiza el usuario -dentro de su aplicación. -Para obtener más información sobre cómo utilizar los diálogos y los avisos, consulte -<a href="/design/patterns/confirming-acknowledging.html">Confirmación y reconocimiento</a>.</p> - -<h3>Orden y clasificación</h3> - -<p>Las notificaciones son noticias que, como tales, se muestran, básicamente, en -orden cronológico inverso, prestando -especial atención a la -<a href="#correctly_set_and_manage_notification_priority">prioridad</a> de la notificación especificada en la aplicación.</p> - -<p>Las notificaciones son una parte clave de la pantalla de bloqueo y se muestran de forma prominente -cada vez -que se enciende la pantalla del dispositivo. El espacio en la pantalla de bloqueo es reducido, por lo que -es sumamente importante -que se identifiquen las notificaciones más urgentes o relevantes. Por este -motivo, Android cuenta -con un algoritmo de clasificación más sofisticado para las notificaciones, que tiene en cuenta lo siguiente:</p> - -<ul> - <li> La marca de tiempo y la prioridad especificada en la aplicación.</li> - <li> Si la notificación interrumpió al usuario recientemente con un sonido o una -vibración. (Es decir, - si el teléfono emitió un sonido y el usuario desea saber "¿Qué -pasó?", en la pantalla de bloqueo se debe - proporcionar una respuesta a simple vista).</li> - <li> Todas aquellas personas involucradas en la notificación mediante{@link android.app.Notification#EXTRA_PEOPLE} - y, especialmente, si son contactos preferidos.</li> -</ul> - -<p>Para aprovechar aún más esta función de clasificación, enfóquese en la -experiencia del usuario que desea -crear, en lugar de centrarse en algún punto importante de la lista.</p> - - <img src="{@docRoot}images/android-5.0/notifications/AntiSample3.png" alt="" width="700px" /> - - <p class="img-caption" style="margin-top:10px">Las notificaciones de Gmail -poseen una prioridad predeterminada, por lo que - normalmente clasifican los mensajes de una aplicación de mensajería instantánea como Hangouts, pero -realizan - un cambio de prioridad temporal cuando ingresan nuevos mensajes. - </p> - - -<h3>En la pantalla de bloqueo</h3> - -<p>Como las notificaciones son visibles en la pantalla de bloqueo, la privacidad del usuario es un aspecto -especialmente -importante. Por lo general, las notificaciones contienen información confidencial y -no necesariamente deben ser visibles -para cualquier persona que agarre el dispositivo y encienda la pantalla.</p> - -<ul> - <li> En el caso de los dispositivos que posean una pantalla de bloqueo segura (PIN, patrón o contraseña), la interface está formada por - partes públicas y privadas. La interfaz pública se puede mostrar en una pantalla de bloqueo segura y, - por ende, cualquier persona puede verla. La interfaz privada es el mundo detrás de esa pantalla de bloqueo y - solo se revela cuando el usuario se registra en el dispositivo.</li> -</ul> - -<h3>Control del usuario sobre la información que se muestra en la pantalla de bloqueo segura</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/LockScreen@2x.png" srcset="{@docRoot}images/android-5.0/notifications/LockScreen.png 1x" alt="" width="311px" /> - <p class="img-caption"> - Notificaciones en la pantalla de bloqueo, en la que el contenido se revela luego de que el usuario desbloquea el dispositivo - </p> -</div> - -<p>Cuando se configura una pantalla de bloqueo segura, el usuario puede decidir ocultar los -detalles confidenciales de dicha pantalla. En este caso, la IU del sistema -analiza el <em>nivel de visibilidad</em> de la notificación para decidir -qué información se puede mostrar de forma segura.</p> -<p> Para controlar el nivel de visibilidad, realice una llamada a -<code><a -href="/reference/android/app/Notification.Builder.html#setVisibility(int)">Notification.Builder.setVisibility()</a></code> - y especifique uno de los siguientes valores:</p> - -<ul> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PUBLIC">VISIBILITY_PUBLIC</a></code>. -Se muestra todo el contenido de la notificación. - Esta es la opción predeterminada del sistema si no se especificó el grado de visibilidad.</li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PRIVATE">VISIBILITY_PRIVATE</a></code>. -En la pantalla de bloqueo se muestra la información básica sobre la existencia de esta notificación, incluido -el icono y el nombre de la aplicación a través de la cual se publicó. No se muestra el resto de los detalles de la notificación. -A continuación, especificamos algunos puntos que se deben tener en cuenta: - <ul> - <li> Si desea proporcionar una versión pública diferente de su notificación -para que el sistema la muestre en una pantalla de bloqueo segura, suministre un -objeto de notificación de reemplazo en el campo <code><a -href="/reference/android/app/Notification.html#publicVersion">Notification.publicVersion</a></code> -. - <li> Mediante esta configuración, su aplicación puede crear una versión resumida del -contenido que sigue siendo útil, pero que no revela información personal. Considere el ejemplo de una -aplicación de SMS cuyas notificaciones incluyen el texto del SMS, el nombre del remitente y el icono del contacto. -Esta notificación debe ser <code>VISIBILITY_PRIVATE</code>, pero <code>publicVersion</code> podría -seguir conteniendo información útil como "3 mensajes nuevos", sin que se muestren otros detalles -de identificación. - </ul> - </li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_SECRET">Notification.VISIBILITY_SECRET</a></code>. Se muestra solo la menor cantidad de información posible; se excluye incluso -el icono de la notificación.</li> -</ul> -<h2 style="clear:both" id="notifications_on_android_wear">Notificaciones en -Android Wear</h2> - -<p>Las notificaciones y sus <em>acciones</em> se conectan de forma predeterminada con los dispositivos con Wear. -Los desarrolladores pueden controlar qué notificaciones se conectan desde el -teléfono hacia el reloj -y viceversa. Los desarrolladores también pueden controlar qué acciones se conectan. Si -en su aplicación se incluyen -acciones que no se pueden realizar con una sola pulsación, oculte dichas acciones -en su notificación para Wear -o considere anclarlas a una aplicación de Wear. De este modo, el usuario podrá -finalizar con la acción desde el -reloj.</p> - -<h4>Conexión entre notificaciones y acciones</h4> - -<p>Mediante un dispositivo conectado, como un teléfono, es posible conectar las notificaciones con un dispositivo con Wear, para que las -notificaciones se muestren allí. De modo similar, también es posible conectar acciones para que el usuario pueda ejecutarlas -directamente desde las notificaciones en los dispositivos con Wear.</p> - -<p><strong>Conexión</strong></p> - -<ul> - <li> Nuevos mensajes instantáneos</li> - <li> Acciones de una sola pulsación como Hacer +1, Me gusta o Favorito</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/WearBasic.png" width="156px" height="156px" alt="" /> - -<p><strong>Sin conexión</strong></p> - -<ul> - <li> Notificaciones de podcasts que llegaron recientemente</li> - <li> Acciones que se asignan a funciones que no se pueden ejecutar desde el reloj</li> -</ul> - - - -<p><h4>Acciones únicas diseñadas para Wear</h4></p> - -<p>Existen algunas acciones que solo puede realizar en Wear. Entre estas, se incluyen las siguientes:</p> - -<ul> - <li> listas rápidas de respuestas predeterminadas como "Vuelvo enseguida";</li> - <li> acciones que se abren desde el teléfono;</li> - <li> un "Comentario" o una acción de "Respuesta" que activa la pantalla de entrada de voz;</li> - <li> acciones que lanzan aplicaciones específicas de Wear.</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/ReplyAction.png" width="156px" height="156px" alt="" /> diff --git a/docs/html-intl/intl/ja/design/patterns/notifications.jd b/docs/html-intl/intl/ja/design/patterns/notifications.jd deleted file mode 100644 index 8c5b6babd085..000000000000 --- a/docs/html-intl/intl/ja/design/patterns/notifications.jd +++ /dev/null @@ -1,872 +0,0 @@ -page.title=通知 -page.tags="notifications","design","L" -@jd:body - - <a class="notice-developers" href="{@docRoot}training/notify-user/index.html"> - <div> - <h3>デベロッパー文書</h3> - <p>ユーザーに通知する</p> - </div> -</a> - -<a class="notice-designers" href="notifications_k.html"> - <div> - <h3>Android 4.4 以前での通知</h3> - </div> -</a> - -<!-- video box --> -<a class="notice-developers-video" href="https://www.youtube.com/watch?v=Uiq2kZ2JHVY"> -<div> - <h3>ビデオ</h3> - <p>DevBytes:Notifications in the Android L Developer Preview</p> -</div> -</a> - -<style> - .col-5, .col-6, .col-7 { - margin-left:0px; - } -</style> - -<p>通知システムを使用すると、ユーザーは友人からの新しいチャット メッセージやカレンダー イベントなど、自分に関係のあるタイムリーなイベントについてアプリで常に通知を受けることができます。通知は、重要な出来事が起こるとすぐに知らせてくれるニュース チャンネルであり、ユーザーが意識していない間に出来事を時系列的に記録するログであると捉えることができます — さらに、すべての Android 端末で適宜同期されます。 - - - - - -</p> - -<h4 id="New"><strong>Android 5.0 での新機能</strong></h4> - -<p>Android 5.0 において、通知は構造的に、視覚的に、機能的に重要なアップデートを受信します。 -</p> - -<ul> - <li>通知は、新しいマテリアル デザインのテーマにあわせて外観が変更されているところす。 -</li> - <li> 端末のロック画面で通知を利用できるようになりましたが、機密性の高いコンテンツはこれからも非表示にできます。 - -</li> - <li>端末の使用中に受信した高優先度の通知において、ヘッドアップ通知と呼ばれる新しい形式が使用されるようになりました。 -</li> - <li>クラウド同期通知: 所有する Android 端末のどれかで通知を却下すると、他でも却下されます。 - -</li> -</ul> - -<p class="note"><strong>注</strong>: このバージョンの Android での通知設計は、従来のバージョンから大きく変わっています。 - -これまでのバージョンの通知設計について詳しくは、<a href="./notifications_k.html">Android 4.4 以前での通知</a>をご覧ください。 -</p> - -<h2 id="Anatomy">通知の仕組み</h2> - -<p>このセクションでは、通知の基本パーツと各種端末における通知の表示について詳しく説明します。 -</p> - -<h3 id="BaseLayout">基本レイアウト</h3> - -<p>あらゆる通知の最低限の基本レイアウトは次のようになっています。</p> - -<ul> - <li> 通知の<strong>アイコン</strong>。このアイコンは通知元のアプリを示します。複数タイプの通知を生成するアプリでは、通知のタイプを示すことがあります。 - - -</li> - <li> 通知の<strong>タイトル</strong>と追加<strong>テキストメッセージ</strong>。 -</li> - <li> <strong>タイムスタンプ</strong>。</li> -</ul> - -<p>従来のプラットフォーム バージョンの {@link android.app.Notification.Builder Notification.Builder} で作成された通知は、Android 5.0 でも同じように表示され、機能します。スタイルにいくらかの違いがありますが、システムが対処します。 - - -従来のバージョンの Android での通知について詳しくは、<a href="./notifications_k.html">Android 4.4 以前での通知</a>をご覧ください。 - -</p></p> - - - <img style="margin:20px 0 0 0" src="{@docRoot}images/android-5.0/notifications/basic_combo.png" alt="" width="700px" /> - - -<div style="clear:both;margin-top:20px"> - <p class="img-caption"> - ユーザー フォトと通知アイコンを使用した、携帯端末での通知(左)と Wear での同じ通知(右) - - </p> - </div> - -<h3 id="ExpandedLayouts">展開レイアウト</h3> - - -<p>通知にどこまでの詳細を表示するかを選択できます。 -メッセージの最初の数行を表示したり、大きな画像プレビューを表示したりできます。 -追加情報はユーザーにより多くのコンテキストを提供し、—場合によっては—メッセージ全体が表示されることもあります。 - - -ユーザーは、ピンチ ズームまたは 1 本指のスワイプで、コンパクトなレイアウトと展開されたレイアウトを切り替えることができます。 - - - 1 つのイベントに関する通知に対し、Android では 3 種類の展開レイアウト(テキスト、受信トレイ、画像)をアプリケーションで使用できるようにしています。 - -次の図に、1 つのイベントに関する通知が携帯端末(左)とウェアラブル(右)でどのように見えるかを示します。 - -</p> - -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/expandedtext_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/stack_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/ExpandedImage.png" - alt="" width="311px" height;="450px" /> - -<h3 id="actions" style="clear:both; margin-top:40px">アクション</h3> - -<p>Android では、通知の最下部に表示されるオプションのアクションをサポートしています。ここに示されるアクションを使用することで、ユーザーは特定の通知に対するほとんどの一般的なタスクを通知シェードで処理でき、通知元のアプリケーションを開く必要はありません。これによりやり取りがスピードアップし、スワイプで却下もできることから、ユーザーは自分に関係のある通知に集中しやすくなります。 - - - - - -</p> - - - <img src="{@docRoot}images/android-5.0/notifications/action_combo.png" alt="" width="700px" /> - - - -<p style="clear:both">通知に含めるアクションの数はほどほどに抑えることをお勧めします。 -含めるアクションを増やすほど、わかりにくくなるからです。 -もっとも差し迫った意味のある重要なアクションだけにして、アクションの数を最小限に抑えてください。 - - -</p> - -<p>通知に対するアクションとして好ましい候補は次のとおりです。</p> - -<ul> - <li> 表示するコンテンツ タイプに欠かせず、よく使われ、典型的である - - <li> ユーザーがタスクを手早く完了できる -</ul> - -<p>次のようなアクションは避けてください。</p> - -<ul> - <li> あいまいである - <li> 通知のデフォルト アクションと同じである(「読む」や「開く」など) - -</ul> - - - -<p>アクションは 3 つまで指定でき、それぞれにアクションのアイコンと名前が付きます。 - - シンプルな基本レイアウトにアクションを追加すると、展開レイアウトがない場合でも、通知は展開可能になります。 - -アクションは展開可能な通知にのみ表示され、それ以外では非表示になることから、ユーザーが通知から起動できるどのアクションについても、関連アプリケーションからも利用できるようにしてください。 - - - - -</p> - -<h2 style="clear:left">ヘッドアップ通知</h2> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/hun-example.png" alt="" width="311px" /> - <p class="img-caption"> - イマーシブ アプリの最上部に表示されたヘッドアップ通知の例(電話の着信、高優先度) - - - </p> -</div> - -<p>優先度の高い通知が作成されると(右図)、その展開レイアウトが可能なアクションとともに短時間表示されます。 - -</p> -<p> この時間が過ぎると、通知は通知シェードに戻ります。 -通知の<a href="#correctly_set_and_manage_notification_priority">優先度</a>を示すフラグが高、最大、全画面の場合は、ヘッドアップ通知になります。 -</p> - -<p><b>ヘッドアップ通知にふさわしい例</b></p> - -<ul> - <li> 端末使用中の電話の着信</li> - <li> 端末使用中のアラーム</li> - <li> 新しい SMS メッセージ</li> - <li> 低バッテリ残量</li> -</ul> - -<h2 style="clear:both" id="guidelines">ガイドライン</h2> - - -<h3 id="MakeItPersonal">パーソナルにする</h3> - -<p>他人から送信されたアイテム(メッセージ、ステータス アップデートなど)の通知には、{@link android.app.Notification.Builder#setLargeIcon setLargeIcon()} を使用して相手の画像を含めます。 - -また、通知のメタデータに相手に関する情報を添付します({@link android.app.Notification#EXTRA_PEOPLE} を参照)。 -</p> - -<p>通知のメインアイコンは表示され続けるため、ユーザーはそれをステータスバーに表示されるアイコンと関連付けることができます。 - -</p> - - -<img src="{@docRoot}images/android-5.0/notifications/Triggered.png" alt="" width="311px" /> -<p style="margin-top:10px" class="img-caption"> - 通知をトリガーした人と送信内容が表示された通知。 -</p> - - -<h3 id="navigate_to_the_right_place">適切な画面へのナビゲーション</h3> - -<p>ユーザーが通知の本体(アクション ボタン以外)をタップしたら、アプリが開き、通知に表示されているデータの表示や操作ができる画面へ移動するようにします。 - - -ほとんどの場合、移動先はメッセージのような 1 つのデータアイテムの詳細表示になりますが、通知がスタックされている場合は概要ビューにすることも考えられます。 - -アプリがユーザーをアプリの最上位レベルより下のどこかに移動する場合は、アプリのバックスタックにナビゲーションを挿入して、ユーザーがシステムの Back ボタンを押すと最上位レベルに戻れるようにします。 - -詳しくは、<a href="{@docRoot}design/patterns/navigation.html#into-your-app">ナビゲーション</a>デザイン パターンの<em>ホーム画面ウィジェットと通知を経由するアプリへのナビゲーション</em>をご覧ください。 - -</p> - -<h3 id="correctly_set_and_manage_notification_priority">通知優先度の適切な設定と管理 - -</h3> - -<p>Android では、通知用の優先度フラグをサポートしています。このフラグを使用すると、通知の表示位置に他の通知との相対関係として影響を及ぼして、ユーザーが常に最重要の通知を真っ先に目にするようにできます。 - - -通知を投稿する際には、優先度を次の中から選べます。 - -</p> -<table> - <tr> - <td class="tab0"> -<p><strong>優先度</strong></p> -</td> - <td class="tab0"> -<p><strong>用途</strong></p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MAX</code></p> -</td> - <td class="tab1"> -<p>重大で切迫した通知に対して使用します。緊急を要する状況、または特定のタスクを続ける前に解決する必要がある状況であることをユーザーに通告します。 - - -</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>HIGH</code></p> -</td> - <td class="tab1"> -<p>主に重要な情報に対して使用します。ユーザーが特に関心を持ちそうなメッセージ イベントやチャット イベントなどが該当します。通知の優先度を高く設定すると、ヘッドアップ通知を表示できます。 - -</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>DEFAULT</code></p> -</td> - <td class="tab1"> -<p>ここで説明している他の優先度のどれにも該当しないすべての通知に対して使用します。</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>LOW</code></p> -</td> - <td class="tab1"> -<p>ユーザーに知らせたいがそれほど緊急ではない通知に対して使用します。 -低優先度の通知は一般にリストの末尾に表示され、公の、または間接的なソーシャル アップデートなどに適しています。 - -ユーザーがこうした通知の設定をしていても、急を要するコミュニケーションや直接的なコミュニケーションより優先されないようにする必要があります。 - - -</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MIN</code></p> -</td> - <td class="tab1"> -<p>天気予報や周辺位置情報のようなコンテキスト的またはバックグラウンド的な情報に対して使用します。最小優先度の通知はステータスバーに表示されません。 - -ユーザーは通知シェードを展開したときにその存在に気づきます。 -</p> -</td> - </tr> -</table> - - -<h4 id="how_to_choose_an_appropriate_priority"><strong>適切な優先度の選び方</strong> - -</h4> - -<p><code>DEFAULT</code>、<code>HIGH</code>、<code>MAX</code> は中断を伴う優先度レベルで、ユーザーによるアクティビティに割り込むリスクがあります。 - -アプリのユーザーに不快に思われないようにするため、割り込みを伴う優先度レベルの通知は次のような場合に限定してください。 -</p> - -<ul> - <li> 他人が絡む</li> - <li> 急を要する</li> - <li> 実世界におけるユーザーの行動が直ちに変わりうる</li> -</ul> - -<p><code>LOW</code> や <code>MIN</code> に設定されている通知も、ユーザーにとって価値がある可能性はあります。 -ほとんどとは言わないまでも、多くの通知は、ユーザーの注意を直ちに引く、またはユーザーの手首に振動を与える必要はありませんが、ユーザーがその通知を見ることにしたときに価値があると気づくような情報が含まれている必要があります。 - - -優先度が <code>LOW</code> や <code>MIN</code> の通知の条件は以下のとおりです。 -</p> - -<ul> - <li> 他人が絡まない</li> - <li> 急を要さない</li> - <li> ユーザーが興味を持ちうる内容が含まれているが、手が空いたときに参照することにして問題ない -</li> -</ul> - - - <img src="{@docRoot}images/android-5.0/notifications/notifications_pattern_priority.png" alt="" width="700" /> - - -<h3 style="clear:both" id="set_a_notification_category">通知カテゴリの設定 -</h3> - -<p>通知が、あらかじめ定義されているカテゴリ(下を参照)のどれかに該当する場合は、それに沿って割り当てます。 - -通知シェード(やその他の通知リスナー)などの各種システム UI は、評価やフィルタリングの判断にこの情報を使用することがあります。 - -</p> -<table> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_CALL">CATEGORY_CALL</a></code></p> -</td> - <td> -<p>電話(ビデオまたは音声)の着信またはそれに類する同期通信の要求 -</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_MESSAGE">CATEGORY_MESSAGE</a></code></p> -</td> - <td> -<p>直接メッセージ(SMS、インスタントメッセージなど)の受信</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EMAIL">CATEGORY_EMAIL</a></code></p> -</td> - <td> -<p>非同期バルク メッセージ(メール)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EVENT">CATEGORY_EVENT</a></code></p> -</td> - <td> -<p>カレンダー イベント</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROMO">CATEGORY_PROMO</a></code></p> -</td> - <td> -<p>販促または広告</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ALARM">CATEGORY_ALARM</a></code></p> -</td> - <td> -<p>アラームまたはタイマー</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROGRESS">CATEGORY_PROGRESS</a></code></p> -</td> - <td> -<p>長時間実行のバックグラウンド処理の進捗</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SOCIAL">CATEGORY_SOCIAL</a></code></p> -</td> - <td> -<p>ソーシャル ネットワークまたは共有アップデート</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ERROR">CATEGORY_ERROR</a></code></p> -</td> - <td> -<p>バックグラウンド処理または認証ステータスにおけるエラー</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_TRANSPORT">CATEGORY_TRANSPORT</a></code></p> -</td> - <td> -<p>再生のためのメディア転送コントロール</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SYSTEM">CATEGORY_SYSTEM</a></code></p> -</td> - <td> -<p>システムまたは端末のステータス アップデート。システム用に予約済み。</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SERVICE">CATEGORY_SERVICE</a></code></p> -</td> - <td> -<p>バックグラウンド サービス実行中の表示。</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_RECOMMENDATION">CATEGORY_RECOMMENDATION</a></code></p> -</td> - <td> -<p>1 つの事項に対する具体的でタイムリーな推奨。たとえば、ニュースアプリがユーザーが次に読みたいのではないかと予想した記事を推奨するなど。 - -</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_STATUS">CATEGORY_STATUS</a></code></p> -</td> - <td> -<p>端末やコンテキスト ステータスに関する進行中情報。</p> -</td> - </tr> -</table> - -<h3 id="summarize_your_notifications">通知の概要</h3> - -<p>アプリで特定の新しい通知を送信しようとしたときに同じタイプの通知が既に保留されていた場合は、それらを統合してそのアプリに対する 1 つの概要通知にします。新しいオブジェクトは作成しないでください。 - -</p> - -<p>概要通知は概要説明を作成し、特定タイプの通知がいくつ保留になっているのかがユーザーにわかるようにします。 - -</p> - -<div class="col-6"> - -<p><strong>非推奨</strong></p> - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Dont.png" alt="" width="311px" /> -</div> - -<div> -<p><strong>推奨</strong></p> - - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Do.png" alt="" width="311px" /> -</div> - -<p style="clear:left; padding-top:30px; padding-bottom:20px">概要を構成している個々の通知に関する詳細は、展開ダイジェスト レイアウトを使用して提示できます。 - -このアプローチにより、ユーザーはどの通知が保留中か、そして関連アプリで詳しく読もうと思うほどそれらに興味があるかを把握しやすくなります。 - - - -</p> -<div class="col-6"> - <img src="{@docRoot}images/android-5.0/notifications/Stack.png" style="margin-bottom:20px" alt="" width="311px" /> - <p class="img-caption"> - 通知の展開された概要と折りたたまれた概要(<code>InboxStyle</code> を使用) - </p> -</div> - -<h3 style="clear:both" id="make_notifications_optional">通知をオプションにする -</h3> - -<p>ユーザーは常に通知を制御できる必要があります。アプリケーションの設定に通知設定アイテムを追加して、ユーザーがアプリの通知を無効にしたり、警告音や振動を使用するかどうかなどのアラート設定を変更したりできるようにしてください。 - - - -</p> - -<h3 id="use_distinct_icons">見分けやすいアイコンにする</h3> -<p>現在保留になっているのがどのタイプの通知なのか、ユーザーが通知エリアを一目で見分けられることが必要です。 - -</p> - -<div class="figure"> - <img src="{@docRoot}images/android-5.0/notifications/ProductIcons.png" alt="" width="420" /> -</div> - - <div><p><strong>推奨</strong></p> - <p>Android アプリが既に提供している通知アイコンを見ながら、独自アプリ用に見かけの十分異なるアイコンを作成する。 - -</p> - - <p><strong>推奨</strong></p> - <p>小さなアイコン用の適切な<a href="/design/style/iconography.html#notification">通知アイコン スタイル</a>と、アクション アイコン用の Material Light <a href="/design/style/iconography.html#action-bar">アクションバー アイコンスタイル</a>を使う。 - - - -</p> -<p ><strong>推奨</strong></p> -<p >アイコンの見た目はシンプルに保ち、細かくしすぎて見にくくならないようにする。 -</p> - - <div><p><strong>非推奨</strong></p> - <p>なんらかの追加アルファ(暗転やフェード)を小さなアイコンやアクション アイコンに配置する。エッジはアンチ エイリアス処理できますが、Android ではこれらのアイコンをマークとして使用するため(つまり、アルファ チャンネルのみ使用)、画像は概して完全不透明で描画されます。 - - - - -</p> - -</div> -<p style="clear:both"><strong>非推奨</strong></p> - -<p>アプリを他と色で区別する。通知アイコンは、背景が透明な白に限定してください。 -</p> - - -<h3 id="pulse_the_notification_led_appropriately">通知 LED を適切に点灯させる -</h3> - -<p>多くの Android 端末には通知 LED が用意されており、スクリーンがオフのときでもユーザーに引き続きイベントを通知するために使用されます。 - -優先度が <code>MAX</code>、<code>HIGH</code>、<code>DEFAULT</code> の通知を LED 点灯するようにし、優先度の低い通知(<code>LOW</code> と <code>MIN</code>)は点灯しないようにしてください。 - - -</p> - -<p>ユーザーによる通知の制御が LED にも及ぶようにしてください。DEFAULT_LIGHTS を使用すると、LED が白く点灯します。 - -ユーザーが明示的にカスタマイズしない限り、通知では別の色を使用しないでください。 - -</p> - -<h2 id="building_notifications_that_users_care_about">ユーザーが気にする通知の作成 -</h2> - -<p>ユーザーに愛されるアプリを開発するためには、通知を入念にデザインすることが重要です。通知はアプリの声を体現するものであり、アプリの個性の一部です。 - - -望まれない通知や重要ではない通知がユーザーの邪魔になったり、アプリへの注目を集める意図が逆にユーザーに不快に思われたりしかねませんので、通知は適切に使用してください。 - - -</p> - -<h3 id="when_to_display_a_notification">通知を表示すべきケース</h3> - -<p>ユーザーが楽しんで使えるアプリケーションを開発するには、ユーザーの注目や関心は保護すべきリソースであるという認識が重要です。 - -Android の通知システムは、ユーザーの注意に対する通知のインパクトを最小限に抑える設計になっていますが、通知がユーザーのタスクフローに割り込むという事実を意識することがやはり重要です。通知を盛り込む予定の場合は、それが割り込みに値するほど重要かどうかを自問してください。 - - - - - - -確信が持てない場合は、ユーザーがアプリの通知設定を使用して通知をコントロールできるようにするか、通知のフラグを <code>LOW</code> か <code>MIN</code> に設定してユーザーがしている別のことを邪魔しないようにします。 - - - -</p> - - <img src="{@docRoot}images/android-5.0/notifications/TimeSensitive.png" alt="" width="311px" /> - <p style="margin-top:10px" class="img-caption"> - 急を要する通知の例 - </p> - -<p>概して、適切に振る舞うアプリは話しかけられたときだけ口を開きますが、求められていない通知でユーザーの作業に割り込むことにメリットがあるケースもいくつか存在します。 -</p> - -<p>通知は主に<strong>急を要するイベント</strong>で、特に<strong>他人が絡む</strong>同期イベントで使用します。 -たとえば、受信チャットはリアルタイムの同期コミュニケーションです。 - -他人が応答を能動的に待っています。 -カレンダー イベントも、通知でユーザーの注目を引くタイミングに関する好例です。なぜなら、そうしたイベントは差し迫っており、往々にして他人が絡みます。 - - -</p> - -<h3 style="clear:both" id="when_not_to_display_a_notification">通知を表示すべきでないケース -</h3> - -<div class="figure" style="margin-top:60px"> - <img src="{@docRoot}images/android-5.0/notifications/AntiSample1.png" alt="" width="311px" /> -</div> - -<p>以上を除く多くの場合、通知の使用は適切ではありません。</p> - -<ul> - <li> 明示的にユーザー宛てではない情報や、それほど急を要さない情報は、ユーザーへの通知を避けます。 - -たとえば、ソーシャル ネットワーク経由で流れてくる非同期の間接的なアップデートは、概してリアルタイムの割り込みにふさわしくありません。 - - -それらに本当に関心のあるユーザーが選択できるようにします。 -</li> - <li> 関連する新しい情報が現在画面に表示されている場合は、通知を作成しないようにします。 -その代わり、アプリケーションそのものの UI を使用して、ユーザーに情報をコンテキスト内で直接通知します。 - - - たとえば、チャット アプリケーションは、ユーザーが他のユーザーとチャットしている最中にシステム通知を作成しないようにします。 -</li> - <li> 情報の保存や同期、アプリケーションのアップデートなど、低レベルの技術的な通知については、アプリやシステムがユーザーの介入なしに問題を解決できる場合は割り込まないようにします。 - -</li> - <li> アプリケーションがユーザーの介入なしにエラーから復旧できる場合は、そのようなエラーの通知で割り込まないでください。 - -</li> - <li> 通知にふさわしい内容がなく、アプリを宣伝するだけの通知は、作成しないようにします。通知は、有益でタイムリーな新しい情報を提供するものであり、アプリを起動するためだけには使用しないでください。 - - - -</li> - <li> ブランドをユーザーの目の前に提示するだけの表面的な通知を作成しないようにします。 - - そうした通知はユーザーにフラストレーションを与え、アプリが使われなくなります。アップデートされた情報を少しだけ提供し、ユーザーをアプリにつなぎ止める最適な方法は、ホームスクリーンに配置できるウィジェットを開発することです。 - - - - -</li> -</ul> - -<h2 style="clear:left" id="interacting_with_notifications">通知の操作 -</h2> - -<p>通知はステータスバーにアイコンとして示され、通知ドロワーを開いてアクセスできます。 - -</p> - -<p>通知をタップすると関連アプリが開き、その通知に対応する詳細なコンテンツに移動します。通知上で左か右にスワイプされた通知は、ドロワーから削除されます。 - -</p> - -<h3 id="ongoing_notifications">進行中通知</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/MusicPlayback.png" alt="" width="311px" /> - <p class="img-caption"> - 音楽再生の進行中通知 - </p> -</div> -<p>進行中通知は、バックグラウンドで進行中の処理に関する情報をユーザーに伝えます。たとえば、音楽プレイヤーは通知システムで現在再生中のトラックを示し、ユーザーが再生を停止するまで通知を継続します。 - - - -進行中通知には、ファイルのダウンロードやビデオのエンコードなど、時間のかかるタスクに対するフィードバックをユーザーに示すこともできます。 - -ユーザーは、進行中通知を通知ドロワーから手動では削除できません。 -</p> - -<h3 id="ongoing_notifications">メディア再生</h3> -<p>Android 5.0 では、廃止された {@link android.media.RemoteControlClient} クラスの転送コントロールがロック画面に表示されません。 -ただし、通知が表示されるため、<em></em>ユーザーがロック状態から再生をコントロールするための主な手段は、現状では各アプリの再生通知です。 - -この動作により、アプリは表示するボタンとその表示形態についてより多くをコントロールでき、画面がロックされているかどうかによらない一貫した操作感をユーザーに提供できます。 - - -</p> - -<h3 style="clear:both" -id="dialogs_and_toasts_are_for_feedback_not_notification">ダイアログとトースト -</h3> - -<p>アプリが画面上に表示されていないときにダイアログやトーストを作成しないようにしてください。 -ダイアログやトーストの表示は、アプリでのアクションに対するユーザーへの即座の応答のみにします。ダイアログやトーストの使用の目安については、<a href="/design/patterns/confirming-acknowledging.html">確認と通知</a>をご覧ください。 - - - -</p> - -<h3>評価と並べ替え</h3> - -<p>通知はニュースであるため、基本的には新しい順に表示され、アプリが通知に指定した<a href="#correctly_set_and_manage_notification_priority">優先度</a>に基づき特別な配慮がなされます。 - - -</p> - -<p>通知はロック画面の重要な一部であり、端末のディスプレイがオンになるたび前面に出ます。 - -ロック画面のスペースは限られているため、もっとも緊急か重要な通知を識別することが何より重要になります。 - -この理由から、Android では洗練された通知並べ替えアルゴリズムを採用しており、その中で以下を考慮しています。 - -</p> - -<ul> - <li> タイムスタンプと、アプリが指定した優先度。</li> - <li> その通知が最近ユーザーに音または振動で配信されたかどうか。 -(つまり、電話が音を立てるだけの場合、ユーザーが「何が起こったのか」を知りたくなったら、ロック画面はそれに一目でわかる答えを示すべきです)。 - - -</li> - <li> {@link android.app.Notification#EXTRA_PEOPLE} を使用して通知に添付された人、特にその人が「お気に入り」の連絡先かどうか。 -</li> -</ul> - -<p>この並べ替え機能を最大限に生かすには、リストにおける特定の位置付けを狙うのではなく、ユーザーの操作感に注目します。 - -</p> - - <img src="{@docRoot}images/android-5.0/notifications/AntiSample3.png" alt="" width="700px" /> - - <p class="img-caption" style="margin-top:10px">Gmail 通知の優先度はデフォルトであり、そのため Hangouts などのインスタントメッセージ アプリからのメッセージの下に並びますが、新しいメッセージが来たときは一時的にそれより先に表示されます。 - - - - - </p> - - -<h3>ロック画面上</h3> - -<p>通知はロック画面に表示されるため、ユーザーのプライバシーはとりわけ重要な考慮対象です。 - -通知には機密性の高い情報が含まれることが多く、端末を手に取ってディスプレイをオンにした誰にでも見られるようにすべきではありません。 - -</p> - -<ul> - <li> セキュリティ保護されたロック画面(PIN、パターン、パスワードなど)を持つ端末の場合、インターフェースには公開部分と秘密部分があります。 -公開インターフェースはセキュリティ保護されたロック画面に表示でき、誰でも見られます。 -秘密インターフェースはロック画面の背後にある世界で、ユーザーが端末にサインインして初めて表示されます。 -</li> -</ul> - -<h3>セキュリティ保護されたロック画面に表示される情報のユーザー コントロール</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/LockScreen@2x.png" srcset="{@docRoot}images/android-5.0/notifications/LockScreen.png 1x" alt="" width="311px" /> - <p class="img-caption"> - ロック画面上の通知。コンテンツはユーザーが端末をロック解除した後に表示されます。 - </p> -</div> - -<p>セキュリティ保護されたロック画面をセットアップする際、ユーザーはセキュリティ保護されたロック画面には表示しない機密性の高い情報を選ぶことができます。 -その場合、システム UI は通知の<em>可視性レベル</em>を考慮して、表示しても問題ない情報を識別します。 - -</p> -<p> 可視性レベルをコントロールするには、<code><a -href="/reference/android/app/Notification.Builder.html#setVisibility(int)">Notification.Builder.setVisibility()</a></code> を呼び出し、次の値のどれかを指定します。 - -</p> - -<ul> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PUBLIC">VISIBILITY_PUBLIC</a></code>。通知の内容がすべて表示されます。 - - 可視性レベルが指定されていない場合は、これがシステム デフォルトです。</li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PRIVATE">VISIBILITY_PRIVATE</a></code>。ロック画面に、その通知の存在に関する基本情報、たとえば通知のアイコンやそれを提示したアプリ名などを表示します。 - -通知のその他の詳細は表示されません。いくつか留意すべき点があります。 - - <ul> - <li> システムがセキュリティ保護されたロック画面に表示するためとして公開バージョンの通知を別に提供する場合は、<code><a -href="/reference/android/app/Notification.html#publicVersion">Notification.publicVersion</a></code> フィールドに代替 Notification オブジェクトを用意します。 - - - - <li> この設定により、アプリは利便性はあるが個人情報は明かさない編集されたバージョンのコンテンツを作成できるようになります。 -SMS アプリを例に考えて見ましょう。通知には SMS のテキストメッセージ、送信者の名前、連絡先アイコンが含まれています。この通知は <code>VISIBILITY_PRIVATE</code> であるべきですが、<code>publicVersion</code> にも "3 件の新しいメッセージ" のような個人を特定する詳細なしでも利便性のある情報を盛り込めます。 - - - - - </ul> - </li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_SECRET">Notification.VISIBILITY_SECRET</a></code>。必要最小限の情報のみ表示し、通知のアイコンさえありません。 -</li> -</ul> -<h2 style="clear:both" id="notifications_on_android_wear">Android Wear での通知 -</h2> - -<p>通知とそのアクション<em></em>は、デフォルトで Wear 端末にブリッジされます。デベロッパーは、どの通知が電話から腕時計へ、またはその逆へブリッジするかを制御できます。 - - -また、どのアクションがブリッジするかも制御できます。タップ 1 回では完了しないアクションがアプリに含まれている場合は、そうしたアクションを Wear 通知では隠すか Wear アプリに接続することを検討してください。いずれにしても、ユーザーがアクションを腕時計で完了できるようにします。 - - - - - -</p> - -<h4>通知とアクションのブリッジ</h4> - -<p>電話のような接続状態の端末は、通知を Wear 端末にブリッジして、通知が腕時計に表示されるようにできます。 -同様に、アクションもブリッジして、ユーザーが通知に Wear 端末で直接対処できるようにできます。 -</p> - -<p><strong>ブリッジする</strong></p> - -<ul> - <li> 新しいインスタントメッセージ</li> - <li> +1、いいね、心拍数のようなタップ 1 回のアクション</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/WearBasic.png" width="156px" height="156px" alt="" /> - -<p><strong>ブリッジしない</strong></p> - -<ul> - <li> 新着ポッドキャストの通知</li> - <li> 腕時計ではできない機能にマップされたアクション</li> -</ul> - - - -<p><h4>Wear 専用に定義されたアクション</h4></p> - -<p>Wear でのみできるアクションがいくつかあります。次に例を挙げます。</p> - -<ul> - <li> 「Be right back」 のような定形応答のクイックリスト</li> - <li> 携帯電話で開く</li> - <li> 音声入力画面を起動する 「Comment」 アクションや 「Reply」 アクション</li> - <li> Wear 専用アプリを起動するアクション</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/ReplyAction.png" width="156px" height="156px" alt="" /> diff --git a/docs/html-intl/intl/ko/design/patterns/notifications.jd b/docs/html-intl/intl/ko/design/patterns/notifications.jd deleted file mode 100644 index aab5eacb313d..000000000000 --- a/docs/html-intl/intl/ko/design/patterns/notifications.jd +++ /dev/null @@ -1,872 +0,0 @@ -page.title=알림 -page.tags="notifications","design","L" -@jd:body - - <a class="notice-developers" href="{@docRoot}training/notify-user/index.html"> - <div> - <h3>개발자 문서</h3> - <p>사용자에게 알리기</p> - </div> -</a> - -<a class="notice-designers" href="notifications_k.html"> - <div> - <h3>Android 4.4 이하 버전의 알림</h3> - </div> -</a> - -<!-- video box --> -<a class="notice-developers-video" href="https://www.youtube.com/watch?v=Uiq2kZ2JHVY"> -<div> - <h3>비디오</h3> - <p>DevBytes: Android L Developer Preview의 알림</p> -</div> -</a> - -<style> - .col-5, .col-6, .col-7 { - margin-left:0px; - } -</style> - -<p>알림 시스템을 사용하면 친구로부터 받은 새 채팅 메시지나 캘린더 이벤트와 같이 앱에서 관련된 -시기 적절한 -이벤트에 대한 알림을 사용자에게 표시할 수 있습니다. -알림을 중요한 -이벤트가 -발생한 경우 사용자에게 이에 대해 알리는 뉴스 채널이나 사용자가 앱에 집중하고 -있지 않은 동안에 이벤트를 시간순으로 기록하는 로그라고 생각하세요. 또한, 적절한 경우 모든 Android 기기에 걸쳐 동기화될 수도 있습니다.</p> - -<h4 id="New"><strong>Android 5.0의 새로운 기능</strong></h4> - -<p>Android 5.0에서는 구조적, -시각적, 그리고 기능적으로 중요한 업데이트를 알림을 통해 받을 수 있습니다.</p> - -<ul> - <li>새로운 -머티어리얼 디자인 테마와 일치하도록 알림이 시각적으로 바뀌었습니다.</li> - <li> 알림이 이제 기기 잠금 화면에 표시되나, -민감한 콘텐츠는 여전히 -숨길 수 있습니다.</li> - <li>기기가 사용 중일 때 수신되는 최우선 순위의 알림은 이제 -헤드업 알림이라는 새로운 형식을 사용합니다.</li> - <li>클라우드와 동기화되는 알림: Android -기기 중 하나에서 알림을 해지하면 -다른 기기에서도 해지됩니다.</li> -</ul> - -<p class="note"><strong>참고:</strong> 이 -Android 버전의 알림 디자인은 이전 버전과 많이 -다릅니다. 이전 -버전의 알림 디자인에 대한 자세한 내용은 <a href="./notifications_k.html">Android 4.4 이하 버전의 알림</a>을 참조하세요.</p> - -<h2 id="Anatomy">알림의 해부학적 구조</h2> - -<p>이 섹션에서는 알림의 기본적인 부분과 다양한 유형의 기기에서 알림이 어떻게 -표시될 수 있는지에 대해 살펴봅니다.</p> - -<h3 id="BaseLayout">기본 레이아웃</h3> - -<p>모든 알림은 기본적으로 다음을 포함하는 기본 레이아웃으로 구성됩니다.</p> - -<ul> - <li> 알림 <strong>아이콘</strong>. 알림 아이콘은 -알림을 발생시킨 앱을 나타냅니다. 또한, -앱이 두 가지 이상의 -유형을 생성하는 경우 알림 유형을 나타낼 수도 있습니다.</li> - <li> 알림 <strong>제목</strong> 및 추가 -<strong>텍스트</strong>.</li> - <li> <strong>타임스탬프</strong>.</li> -</ul> - -<p>이전 플랫폼 버전의 -{@link android.app.Notification.Builder Notification.Builder}로 생성된 알림은 시스템이 대신 -처리하는 사소한 스타일 변화를 제외하면 Android -5.0에서 똑같이 표시되고 동작합니다. 이전 -Android 버전의 알림에 대한 자세한 내용은 -<a href="./notifications_k.html">Android 4.4 이하 버전의 알림</a>을 참조하세요.</p></p> - - - <img style="margin:20px 0 0 0" src="{@docRoot}images/android-5.0/notifications/basic_combo.png" alt="" width="700px" /> - - -<div style="clear:both;margin-top:20px"> - <p class="img-caption"> - 핸드헬드 알림(왼쪽) 및 Wear에서 표시되는 동일한 알림(오른쪽)의 기본 레이아웃 -- 사용자 사진 및 알림 아이콘 포함 - </p> - </div> - -<h3 id="ExpandedLayouts">확장 레이아웃</h3> - - -<p>앱 알림이 얼마나 자세한 정보를 -제공하도록 할지는 직접 선택할 수 있습니다. 메시지의 처음 -몇 줄을 보여주거나 더 큰 이미지 미리보기를 보여줄 수 있습니다. 이러한 추가 -정보는 사용자에게 더 많은 -컨텍스트를 제공하며, 경우에 따라 이를 통해 사용자는 메시지 -전체를 읽을 수도 있습니다. 사용자는 -핀치-줌(pinch-zoom) 또는 한 손가락으로 밀기를 이용하여 축소 레이아웃과 -확장 레이아웃 간을 전환할 수 있습니다. - Android는 단일 이벤트 알림에 대해 세 개의 확장 레이아웃 -템플릿(텍스트, 받은 편지함, -이미지)을 애플리케이션에 사용할 수 있도록 제공합니다. 다음 이미지는 -단일 이벤트 알림이 -핸드헬드(왼쪽) 및 웨어러블(오른쪽)에서 어떻게 표시되는지 보여줍니다.</p> - -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/expandedtext_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/stack_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/ExpandedImage.png" - alt="" width="311px" height;="450px" /> - -<h3 id="actions" style="clear:both; margin-top:40px">작업</h3> - -<p>Android는 알림의 -맨 아래 부분에 표시되는 선택적인 작업을 지원합니다. -이러한 작업을 통해 사용자는 알림을 발생시킨 -애플리케이션을 열 필요 없이 알림 창에서 특정 -알림에 대한 가장 일반적인 태스크를 처리할 수 있습니다. -이 기능은 밀어서 해제하기와 함께 작용하여 상호 작용의 속도를 향상시키며, 사용자가 자신에게 중요한 알림에 -집중하는 데 도움이 됩니다.</p> - - - <img src="{@docRoot}images/android-5.0/notifications/action_combo.png" alt="" width="700px" /> - - - -<p style="clear:both">알림에 -포함할 작업의 수는 신중하게 결정해야 합니다. 더 많은 -작업을 포함할수록 인지적 복합성이 가중됩니다. 당장에 중요하며 의미 -있는 작업만 포함하여 작업 -수를 최소한으로 -제한해야 합니다.</p> - -<p>알림에 포함하기에 적합한 작업은 다음과 같습니다.</p> - -<ul> - <li> 표시하려는 -콘텐츠 유형과 관련하여 필수적이고, 자주 사용되며 전형적인 작업 - <li> 사용자가 신속하게 태스크를 완료할 수 있게 하는 작업 -</ul> - -<p>다음과 같은 작업은 피합니다.</p> - -<ul> - <li> 애매모호한 작업 - <li> "읽기" 또는 -"열기"와 같이 알림의 기본 작업과 동일한 작업 -</ul> - - - -<p>작업 -아이콘 및 이름으로 각각 구성된, 최대 세 개의 작업을 지정할 수 있습니다. - 단순한 기본 레이아웃에 작업을 추가하면 알림이 확장 가능하게 되며, -알림에 -확장 레이아웃이 없는 경우에도 이러한 사항이 적용됩니다. 작업은 -확장된 -알림에서만 표시되고 그 외에는 숨겨져 있으므로 -사용자가 알림에서 -호출할 수 있는 모든 작업을 관련 애플리케이션 내에서도 -사용할 수 있는지 확인해야 합니다.</p> - -<h2 style="clear:left">헤드업 알림</h2> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/hun-example.png" alt="" width="311px" /> - <p class="img-caption"> - 몰입형 앱의 -최상위에 -표시되는 헤드업 알림의 예(걸려오는 전화, 최우선 순위) - </p> -</div> - -<p>최우선 순위의 알림을 수신하면(오른쪽), 가능한 작업을 보여주는 확장된 레이아웃 형태로 -잠시 동안 사용자에게 -표시됩니다.</p> -<p> 그런 다음, 알림이 알림 -창으로 돌아갑니다. 알림에 대한 <a href="#correctly_set_and_manage_notification_priority">우선 순위</a> 플래그가 HIGH, MAX 또는 전체 화면으로 -지정된 경우 헤드업 알림이 표시됩니다.</p> - -<p><b>헤드업 알림의 좋은 예</b></p> - -<ul> - <li> 기기 사용 시 걸려오는 전화</li> - <li> 기기 사용 시 알람</li> - <li> 새 SMS 메시지</li> - <li> 배터리 부족</li> -</ul> - -<h2 style="clear:both" id="guidelines">가이드라인</h2> - - -<h3 id="MakeItPersonal">개인에 맞게 만들기</h3> - -<p>다른 사람이 보낸 항목(메시지 또는 -상태 업데이트)에 대한 알림의 경우 -{@link android.app.Notification.Builder#setLargeIcon setLargeIcon()}을 사용하여 그 사람의 이미지를 포함합니다. 또한 -그 사람에 대한 정보를 알림의 메타데이터에 추가합니다({@link android.app.Notification#EXTRA_PEOPLE} 참조).</p> - -<p>알림의 기본 아이콘이 여전히 표시됩니다. 따라서 사용자는 -해당 아이콘을 상태 표시줄에 -보이는 아이콘과 관련시킬 수 있습니다.</p> - - -<img src="{@docRoot}images/android-5.0/notifications/Triggered.png" alt="" width="311px" /> -<p style="margin-top:10px" class="img-caption"> - 누가 트리거했는지와 보낸 내용을 보여주는 알림입니다. -</p> - - -<h3 id="navigate_to_the_right_place">적합한 곳으로 이동하기</h3> - -<p>사용자가 작업 -버튼 외부에서 알림을 터치하면, 사용자가 알림에서 -참조되는 데이터를 확인하고 처리할 수 있는 곳에서 -앱이 열리도록 합니다. 대부분의 경우, 메시지와 같은 단일 데이터 항목을 표시하는 상세 뷰가 이에 해당합니다. -하지만 알림이 중첩되어 있을 경우에는 -요약 뷰일 수도 있습니다. 앱이 -최상위 레벨 아래의 위치에서 열린 경우 -사용자가 시스템의 뒤로 버튼을 눌러 최상위 레벨로 돌아갈 수 있도록 앱의 백 스택에 탐색 경로를 삽입합니다. 자세한 내용은 -<a href="{@docRoot}design/patterns/navigation.html#into-your-app">탐색</a> -디자인 패턴의 <em>홈 화면 위젯 및 알림을 통한 앱 탐색</em>을 참조하세요.</p> - -<h3 id="correctly_set_and_manage_notification_priority">알림의 -우선 순위를 정확하게 설정하고 -관리하기</h3> - -<p>Android는 알림 우선 순위 플래그를 지원합니다. 이 플래그를 통해 다른 알림에 상대적으로 알림이 표시되는 위치가 -결정되도록 할 수 있습니다. 또한 -사용자가 가장 중요한 알림을 항상 가장 먼저 볼 수 있게 -할 수 있습니다. 알림을 게시할 때 -다음 우선 순위 중에서 -선택할 수 있습니다.</p> -<table> - <tr> - <td class="tab0"> -<p><strong>우선 순위</strong></p> -</td> - <td class="tab0"> -<p><strong>용도</strong></p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MAX</code></p> -</td> - <td class="tab1"> -<p>시간에 민감한 -또는 -특정 태스크를 계속 진행하기 전에 처리해야 할 -상황을 사용자에게 알리는 중요하고 긴급한 알림에 사용합니다.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>HIGH</code></p> -</td> - <td class="tab1"> -<p>중요한 대화에 주로 사용합니다. 일례로 사용자에게 특별히 흥미로운 내용이 포함된 메시지 또는 채팅 -이벤트가 이에 해당합니다. -최우선 순위의 알림은 헤드업 알림이 표시되도록 합니다.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>DEFAULT</code></p> -</td> - <td class="tab1"> -<p>여기서 설명하지 않은 기타 모든 우선 순위의 알림에 사용합니다.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>LOW</code></p> -</td> - <td class="tab1"> -<p>사용자에게 알려야 하지만 긴급하지 않은 -알림에 사용합니다. 우선 순위가 낮은 알림은 보통 목록의 맨 아래에 표시되며, -공개 또는 대상이 불특정한 소셜 업데이트에 사용하기 -좋습니다. 사용자가 -요구한 -알림이지만, 이러한 알림은 긴급하거나 직접적인 -대화를 우선할 수 없습니다.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MIN</code></p> -</td> - <td class="tab1"> -<p>날씨 정보 또는 상황에 맞는 -위치 정보와 같은 상황별 또는 배경 정보에 사용합니다. -최소 우선 순위 알림은 상태 표시줄에 표시되지 않습니다. 이러한 알림은 사용자가 알림 창을 확대하면 -볼 수 있습니다.</p> -</td> - </tr> -</table> - - -<h4 id="how_to_choose_an_appropriate_priority"><strong> -적절한 -우선 순위를 선택하는 방법</strong></h4> - -<p><code>DEFAULT</code>, <code>HIGH</code> 및 <code>MAX</code>는 작업을 중단시키는 우선 순위이며, 사용자의 액티비티를 -중단시키는 -위험 요소입니다. 앱 사용자를 성가시게 하지 않으려면 다음과 같은 -알림에만 작업을 중단시키는 우선 순위를 지정해야 합니다.</p> - -<ul> - <li> 다른 사람이 관련된 알림</li> - <li> 시간에 민감한 알림</li> - <li> 실제 환경에서의 사용자 행동을 즉시 바꿀 수 있는 알림</li> -</ul> - -<p><code>LOW</code> 및 <code>MIN</code>으로 설정된 알림도 사용자에게 -중요할 수 있습니다. 대부분은 아니지만 많은 알림이 사용자의 -즉각적인 주의를 필요로 하지 않거나 사용자의 손목에 진동을 줄 필요가 없지만, 사용자가 알림을 확인하고자 -했을 때 유용하다고 -여길 정보를 포함합니다. <code>LOW</code> 및 <code>MIN</code> -우선 순위 알림에 대한 조건은 다음과 같습니다.</p> - -<ul> - <li> 다른 사람이 관련되지 않음</li> - <li> 시간에 민감하지 않음</li> - <li> 사용자가 흥미를 가질 만하지만 시간이 있을 때 -보기를 원할 수 있는 내용을 포함함</li> -</ul> - - - <img src="{@docRoot}images/android-5.0/notifications/notifications_pattern_priority.png" alt="" width="700" /> - - -<h3 style="clear:both" id="set_a_notification_category">알림 -범주 설정하기</h3> - -<p>알림이 미리 정의된 범주에 포함될 경우(아래 -참조), -그에 따라 할당합니다. 알림 창(또는 -다른 알림 -수신자)과 같은 시스템 UI의 기능은 순위 및 필터링 결정을 내리는 데 이 정보를 활용할 수 있습니다.</p> -<table> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_CALL">CATEGORY_CALL</a></code></p> -</td> - <td> -<p>수신 전화(음성 또는 화상) 또는 이와 유사한 동기적 대화 -요청</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_MESSAGE">CATEGORY_MESSAGE</a></code></p> -</td> - <td> -<p>수신되는 직접 메시지(SMS, 인스턴트 메시지 등)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EMAIL">CATEGORY_EMAIL</a></code></p> -</td> - <td> -<p>비동기적 대량 메시지(이메일)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EVENT">CATEGORY_EVENT</a></code></p> -</td> - <td> -<p>캘린더 이벤트</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROMO">CATEGORY_PROMO</a></code></p> -</td> - <td> -<p>홍보 또는 광고</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ALARM">CATEGORY_ALARM</a></code></p> -</td> - <td> -<p>알람 또는 타이머</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROGRESS">CATEGORY_PROGRESS</a></code></p> -</td> - <td> -<p>장기간 실행 중인 백그라운드 작업의 진행 상황</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SOCIAL">CATEGORY_SOCIAL</a></code></p> -</td> - <td> -<p>소셜 네트워크 또는 공유 업데이트</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ERROR">CATEGORY_ERROR</a></code></p> -</td> - <td> -<p>백그라운드 작업 또는 인증 상태 오류</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_TRANSPORT">CATEGORY_TRANSPORT</a></code></p> -</td> - <td> -<p>재생에 대한 미디어 전송 제어</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SYSTEM">CATEGORY_SYSTEM</a></code></p> -</td> - <td> -<p>시스템 또는 기기 상태 업데이트. 시스템용으로 예약됨</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SERVICE">CATEGORY_SERVICE</a></code></p> -</td> - <td> -<p>실행 중인 백그라운드 서비스에 대한 표시</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_RECOMMENDATION">CATEGORY_RECOMMENDATION</a></code></p> -</td> - <td> -<p>한 가지 특정 항목에 대한 구체적이고 시기적절한 권장 사항. 예를 들어, 뉴스 -앱이 사용자가 다음으로 읽기 원할 것이라고 생각하는 뉴스를 -권하고자 하는 경우</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_STATUS">CATEGORY_STATUS</a></code></p> -</td> - <td> -<p>기기 또는 상황별 상태에 대한 지속적인 정보</p> -</td> - </tr> -</table> - -<h3 id="summarize_your_notifications">알림 요약하기</h3> - -<p>특정 유형의 알림이 이미 보류 중일 때 앱에서 같은 유형의 새 -알림을 보내려고 하는 경우, 이 앱에 대해 두 알림을 하나의 요약 알림으로 결합합니다. 새로운 개체는 -생성하지 않아야 합니다.</p> - -<p>요약 알림은 사용자가 특정 종류의 알림이 -몇 개나 보류 중인지 -파악할 수 있도록 간단한 개요를 표시합니다.</p> - -<div class="col-6"> - -<p><strong>잘못된 사용</strong></p> - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Dont.png" alt="" width="311px" /> -</div> - -<div> -<p><strong>올바른 사용</strong></p> - - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Do.png" alt="" width="311px" /> -</div> - -<p style="clear:left; padding-top:30px; padding-bottom:20px">확장된 다이제스트 레이아웃을 사용하여 -요약에 포함된 각각의 알림에 대한 -더 자세한 정보를 제공할 수 있습니다. 이 방식을 통해 사용자는 -어떠한 알림이 보류 중이고, -관련된 앱에서 -상세 정보를 읽고 싶을 정도로 알림이 흥미로운지를 -판단할 수 있습니다.</p> -<div class="col-6"> - <img src="{@docRoot}images/android-5.0/notifications/Stack.png" style="margin-bottom:20px" alt="" width="311px" /> - <p class="img-caption"> - 확장된 알림 및 축소된 요약 알림(<code>InboxStyle</code> 사용) - </p> -</div> - -<h3 style="clear:both" id="make_notifications_optional">알림을 -선택 항목으로 만들기</h3> - -<p>사용자는 항상 알림을 통제할 수 있어야 합니다. 애플리케이션 설정에 알림 설정 항목을 추가하여 -사용자가 앱의 -알림을 -해제하거나 경고 속성(예: 경고음 및 진동 사용 -여부)을 변경할 수 있도록 허용합니다.</p> - -<h3 id="use_distinct_icons">뚜렷한 아이콘 사용</h3> -<p>알림 영역을 봄으로써 사용자는 현재 -어떠한 종류의 -알림이 보류 중인지 파악할 수 있어야 합니다.</p> - -<div class="figure"> - <img src="{@docRoot}images/android-5.0/notifications/ProductIcons.png" alt="" width="420" /> -</div> - - <div><p><strong>올바른 사용</strong></p> - <p>Android 앱이 이미 제공하는 알림 아이콘을 살펴본 후 본인의 앱에서 -뚜렷히 나타날 수 있는 -알림 아이콘을 만듭니다.</p> - - <p><strong>올바른 사용</strong></p> - <p>작은 아이콘에 -적절한 <a href="/design/style/iconography.html#notification">알림 아이콘 스타일</a>을 사용하며, 작업 -아이콘에는 머티어리얼 라이트 -<a href="/design/style/iconography.html#action-bar">작업 모음 아이콘 -스타일</a>을 사용합니다.</p> -<p ><strong>올바른 사용</strong></p> -<p >아이콘은 시각적으로 단순하게 유지하고, -알아차리기 힘들 정도로 과도하게 세부적인 디자인은 피합니다.</p> - - <div><p><strong>잘못된 사용</strong></p> - <p>작은 -아이콘 및 작업 -아이콘에 알파(어둡게 설정 또는 페이드 효과)를 추가합니다. 아이콘의 가장자리를 안티-앨리어싱할 수는 있지만, Android가 이러한 -아이콘을 마스크(즉, -알파 채널만 사용됨)로 사용하기 때문에 일반적으로 이미지는 최대 수준의 -불투명도로 그려집니다.</p> - -</div> -<p style="clear:both"><strong>잘못된 사용</strong></p> - -<p>다른 앱과의 차별화를 위해 색상을 사용합니다. 알림 아이콘은 투명한 배경 이미지에 흰색 아이콘이어야만 -합니다.</p> - - -<h3 id="pulse_the_notification_led_appropriately">알림 LED를 -적절하게 사용하기</h3> - -<p>많은 Android 기기에는 알림 LED가 내장되어 있으며, 이러한 알림 LED는 화면이 꺼져 있을 때 -사용자에게 -이벤트에 대해 알리기 위해 사용됩니다. 우선 순위가 <code>MAX</code>, -<code>HIGH</code> 또는 <code>DEFAULT</code>인 알림의 경우 -LED가 켜지며, 낮은 우선 순위(<code>LOW</code> 및 -<code>MIN</code>)의 알림의 경우 LED가 켜지지 않습니다.</p> - -<p>알림과 관련하여 사용자는 LED도 제어할 수 있어야 합니다. -DEFAULT_LIGHTS를 사용하는 경우 -LED는 흰색으로 켜집니다. 사용자가 -명시적으로 지정한 경우 외에는 다른 알림 -색상을 사용할 수 없습니다.</p> - -<h2 id="building_notifications_that_users_care_about">사용자가 관심을 가질 만한 -알림 만들기</h2> - -<p>사용자의 사랑을 받는 앱을 만들기 위해서는 -알림을 신중하게 디자인해야 합니다. -알림은 앱의 목소리를 대변하며, 앱의 -개성에 큰 영향을 미칩니다. 원하지 않거나 -중요하지 않은 알림은 사용자를 성가시게 하거나 앱에서 -많은 신경을 -쓰게 하는 것에 대해 짜증이 나게 합니다. 따라서 알림을 사용할 때는 현명하게 판단해야 합니다.</p> - -<h3 id="when_to_display_a_notification">알림을 표시해야 하는 경우</h3> - -<p>사람들이 즐겨 사용하는 애플리케이션을 만들려면 사용자의 -주의와 집중을 흐트러뜨리지 않고 보호해야 하는 리소스임을 -인지하는 것이 중요합니다. Android의 -알림 시스템은 알림이 사용자의 주의를 최대한 방해하지 않도록 -디자인되었습니다. -하지만 -알림이 -사용자의 태스크 흐름을 방해한다는 사실을 계속해서 인지해야 합니다. -알림을 계획할 때 알림이 사용자의 작업을 중단할 만큼 -중요한지 곰곰히 생각해 보시기 바랍니다. 잘 모르겠는 경우, 사용자가 앱의 알림 설정을 사용하여 알림에 대한 수신 동의를 -선택할 수 있도록 허용하거나 알림 우선 순위 플래그를 <code>LOW</code> 또는 <code>MIN</code>으로 -조정하여 사용자 작업을 -방해하지 -않도록 합니다.</p> - - <img src="{@docRoot}images/android-5.0/notifications/TimeSensitive.png" alt="" width="311px" /> - <p style="margin-top:10px" class="img-caption"> - 시간에 민감한 알림의 예 - </p> - -<p>일반적으로 잘 만들어진 앱은 사용자의 요청이 있을 때에만 정보를 알리고 -요청하지 않은 알림은 꼭 필요한 경우에만 표시하도록 합니다.</p> - -<p>알림은 <strong>시간에 민감한 이벤트</strong>에 주로 사용하며, 특히 -이러한 동기적 이벤트에 <strong>다른 사람이 관련된 경우</strong>에 사용합니다. 예를 -들어 수신되는 채팅 메시지는 -실시간으로 진행되는 동기적 대화 형식이며, 이때 다른 사람은 -적극적으로 응답을 기다립니다. 캘린더 이벤트는 언제 -알림을 사용하고 -사용자의 주의를 끌어야 하는지에 대해 알 수 있는 또 다른 좋은 예입니다. 왜냐하면 이는 임박한 이벤트이며, 캘린더 이벤트에는 종종 다른 사람이 -관련되기 때문입니다.</p> - -<h3 style="clear:both" id="when_not_to_display_a_notification">알림을 -표시하지 않아야 하는 경우</h3> - -<div class="figure" style="margin-top:60px"> - <img src="{@docRoot}images/android-5.0/notifications/AntiSample1.png" alt="" width="311px" /> -</div> - -<p>다른 대부분의 경우 알림은 적합하지 않습니다.</p> - -<ul> - <li> 사용자와 -직접 관련이 없는 정보나 시간에 민감하지 않은 -정보는 알리지 않도록 합니다. 예를 들어 소셜 네트워크를 통한 비동기적이며 -대상이 불특정한 업데이트는 -일반적으로 실시간으로 -사용자를 방해할 수 없습니다. 그러한 업데이트를 원하는 사용자의 -경우에는 사전에 수신 동의를 설정할 수 있게 하면 됩니다.</li> - <li> 관련된 새 정보가 현재 -화면에 표시된 경우에는 알림을 생성하지 않아야 합니다. 대신 애플리케이션 UI를 -사용하여 컨텍스트 내에 새로운 정보가 있음을 사용자에게 -직접 알립니다. - 예를 들어 채팅 애플리케이션은 -사용자가 다른 사용자와 대화 중일 때는 시스템 알림을 생성하지 않아야 합니다.</li> - <li> 정보 저장 -또는 동기화, 애플리케이션 업데이트와 같은 낮은 수준의 기술 정보의 경우 사용자가 개입하지 -않아도 앱이나 시스템에서 스스로 알아서 처리할 수 있다면 사용자를 방해하지 않도록 합니다.</li> - <li> 사용자가 아무런 조치를 -취하지 않아도 애플리케이션 스스로 오류를 복구할 -수 있는 경우, 이러한 오류에 대해 사용자에게 알리지 않도록 합니다.</li> - <li> 알리는 내용은 없고 -단순히 앱을 -홍보하는 알림은 만들지 않습니다. 알림은 유용하고, 시기적절하며 새로운 정보를 제공해야 하며, 단지 앱 출시를 위한 용도로는 -사용하지 -않습니다.</li> - <li> 단지 -사용자에게 브랜드를 알리기 위한 불필요한 알림은 만들지 않도록 합니다. - 그러한 알림은 사용자를 짜증 나게 만들어 앱에 대한 관심을 멀어지게 합니다. 소량의 -업데이트된 정보를 제공하면서 사용자가 지속적으로 -앱에 관심을 -갖게 만드는 최고의 -방법은 -홈 화면에 추가할 수 있는 위젯을 개발하는 것입니다.</li> -</ul> - -<h2 style="clear:left" id="interacting_with_notifications">알림과 -상호 작용하기</h2> - -<p>알림은 상태 표시줄에 아이콘으로 표시되며, -알림 창을 열어서 -확인할 수 있습니다.</p> - -<p>알림을 터치하면 관련 앱이 열리고 알림에 -해당되는 세부 내용이 표시됩니다. 알림을 왼쪽이나 오른쪽으로 -스와이프하면 알림 창에서 제거됩니다.</p> - -<h3 id="ongoing_notifications">지속적인 알림</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/MusicPlayback.png" alt="" width="311px" /> - <p class="img-caption"> - 음악 재생으로 인한 지속적인 알림 - </p> -</div> -<p>지속적인 알림은 -백그라운드에서 진행 중인 프로세스에 대해 사용자에게 알립니다. -예를 들어 음악 플레이어는 사용자가 재생을 멈출 때까지 -알림 시스템 내에 현재 재생 중인 트랙을 -계속 표시합니다. 또한 지속적인 알림은 파일을 다운로드하거나 비디오를 인코딩하는 등의 장기 태스크에 대한 -피드백을 사용자에게 -표시할 수도 있습니다. 지속적인 알림은 사용자가 알림 창에서 직접 -제거할 수 없습니다.</p> - -<h3 id="ongoing_notifications">미디어 재생</h3> -<p>Android 5.0에서는 잠금 화면에 사용이 중단된 -{@link android.media.RemoteControlClient} 클래스에 대한 전송 제어가 표시되지 않습니다. 하지만 알림은 <em>표시되며</em>, 각 -앱의 재생 알림이 현재 사용자가 잠금 상태에서 재생을 제어하는 기본 -방법입니다. 이 동작은 화면의 잠금 여부와 상관없이 사용자에게 -일관된 환경을 제공하면서, 어떠한 버튼을 -어떻게 표시할지에 대해 앱이 더 세부적으로 제어할 수 있도록 -지원합니다.</p> - -<h3 style="clear:both" -id="dialogs_and_toasts_are_for_feedback_not_notification">대화 상자 -및 알림 메시지</h3> - -<p>현재 -화면에 표시되어 있는 경우가 아니라면 앱은 대화 상자나 알림 메시지를 생성해서는 안 됩니다. 대화 상자나 알림 메시지는 -앱 내에서 -사용자가 어떠한 행동을 취했을 때 이에 대한 즉각적인 응답으로만 표시되어야 합니다. -대화 상자 및 알림 메시지 사용에 대한 자세한 지침은 -<a href="/design/patterns/confirming-acknowledging.html">확인 및 승인하기</a>를 참조하세요.</p> - -<h3>순위 및 순서</h3> - -<p>알림은 뉴스이므로, 기본적으로 발생한 순서의 역순으로 -표시되며, 특히 -앱에서 명시된 알림 -<a href="#correctly_set_and_manage_notification_priority">우선 순위</a>에 따라 순서가 결정됩니다.</p> - -<p>알림은 잠금 화면에서 중요한 부분이며, 기기의 화면이 켜질 -때마다 -표시됩니다. 잠금 화면의 공간은 협소하기 때문에 가장 긴급하고 관련 있는 알림을 식별하는 것이 -가장 -중요합니다. 이러한 -이유 때문에 Android에는 다음을 고려한 -더욱 정교한 정렬 알고리즘이 있습니다.</p> - -<ul> - <li> 타임스탬프 및 애플리케이션에 명시된 우선 순위.</li> - <li> 알림이 최근에 소리 또는 -진동으로 사용자를 방해했는지에 대한 여부. (즉, -휴대폰에서 방금 소리가 났을 때 사용자가 "방금 무슨 -일이 있었지?"에 대해 알고 싶어하는 경우 잠금 화면을 -보면 한 눈에 알 수 있어야 합니다.)</li> - <li> {@link android.app.Notification#EXTRA_PEOPLE}을 사용하여 알림에 첨부된 사람, -그리고 특히 즐겨찾기에 추가된 연락처인지에 대한 여부.</li> -</ul> - -<p>이러한 정렬 알고리즘을 잘 이용하기 위해서는 목록의 특정 부분에 초점을 두기 보다는 생성하고자 -하는 사용자 -환경에 초점을 둡니다.</p> - - <img src="{@docRoot}images/android-5.0/notifications/AntiSample3.png" alt="" width="700px" /> - - <p class="img-caption" style="margin-top:10px">Gmail 알림은 -기본 우선 순위이기 때문에 -보통은 행아웃과 같은 인스턴트 메시징 앱에서 온 메시지보다 하위에 정렬됩니다. 하지만 -새 메시지가 들어오면 -일시적으로 순위가 올라갑니다. - </p> - - -<h3>잠금 화면</h3> - -<p>알림은 잠금 화면에 표시되기 때문에 사용자의 개인 정보 보호가 -특히 -중요하게 고려해야 할 사항입니다. 알림은 종종 민감한 정보를 포함하기 때문에, 아무나 -기기의 화면을 켰을 때 볼 수 있게 할 필요는 -없습니다.</p> - -<ul> - <li> 보안 잠금 화면(PIN, 패턴 또는 암호)이 있는 기기의 인터페이스에는 -공개 및 비공개 부분이 있습니다. 공개 인터페이스는 보안 잠금 화면에 표시될 수 있기 때문에 -누구나 볼 수 있습니다. 비공개 인터페이스는 잠금 화면 뒤에 있기 때문에 -기기의 잠금 화면을 푼 사람만 볼 수 있습니다.</li> -</ul> - -<h3>보안 잠금 화면에 표시된 정보에 대한 사용자 제어</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/LockScreen@2x.png" srcset="{@docRoot}images/android-5.0/notifications/LockScreen.png 1x" alt="" width="311px" /> - <p class="img-caption"> - 사용자가 기기의 잠금을 푼 후 보이는 콘텐츠와 함께 잠금 화면에 표시된 알림 - </p> -</div> - -<p>보안 잠금 화면을 설정할 때 사용자는 -민감한 세부 정보를 보안 잠금 화면에서 숨기도록 선택할 수 있습니다. 이러한 경우 시스템 UI는 알림의 <em>정보 공개 수준</em>을 -고려하여 -안전하게 표시할 수 있는 정보를 파악합니다.</p> -<p> 정보 공개 수준을 제어하려면 -<code><a -href="/reference/android/app/Notification.Builder.html#setVisibility(int)">Notification.Builder.setVisibility()</a></code>를 호출한 후 -다음 값 중 하나를 지정합니다.</p> - -<ul> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PUBLIC">VISIBILITY_PUBLIC</a></code>. 알림의 전체 내용을 -표시합니다. - 정보 공개 수준을 지정하지 않을 경우 시스템 기본값입니다.</li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PRIVATE">VISIBILITY_PRIVATE</a></code>. -잠금 화면에 알림의 -아이콘과 알림을 게시한 앱의 이름을 포함하여 해당 알림의 존재에 대한 기본 정보를 표시합니다. 알림의 나머지 세부 사항은 표시되지 않습니다. -다음과 같은 몇 가지 유용한 사항을 염두해야 합니다. - <ul> - <li> 시스템이 보안 잠금 화면에 다른 공개 버전의 알림을 -표시하도록 제공하려는 경우, <code><a -href="/reference/android/app/Notification.html#publicVersion">Notification.publicVersion</a></code> -필드에 대체 -알림 개체를 제공해야 합니다. - <li> 이렇게 설정하면 앱에서 여전히 유용하지만 개인 정보를 노출하지 않는 편집된 버전의 -내용을 생성할 수 있습니다. 예를 들어, 알림에 SMS 텍스트, 발신자 이름 및 연락처 아이콘을 포함하는 -SMS 앱이 있다고 가정합니다. -이 알림은 <code>VISIBILITY_PRIVATE</code>여야 하지만, <code>publicVersion</code>은 다른 식별 -정보 없이 "3개의 새 메시지"와 같이 여전히 유용한 정보를 -포함할 수 있습니다. - </ul> - </li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_SECRET">Notification.VISIBILITY_SECRET</a></code>. 최소한의 정보만 표시하며, 알림의 아이콘마저 -표시하지 않습니다.</li> -</ul> -<h2 style="clear:both" id="notifications_on_android_wear">Android Wear에 -표시되는 알림</h2> - -<p>Android Wear에 표시되는 알림과 해당 <em>작업</em>은 기본적으로 Wear 기기에 연결되어 있습니다. -개발자는 어떠한 알림을 -휴대폰에서 워치로, -그리고 그 반대로 연결할지 제어할 수 있습니다. 또한 개발자는 어떠한 작업을 연결할지도 제어할 수 있습니다. 앱이 -단일 탭으로 실행할 수 없는 -작업을 포함하는 경우, 이러한 작업을 -Wear -알림에 표시되지 않도록 숨기거나 Wear 앱에 연결하여 사용자가 -워치에서 작업을 -끝낼 수 있도록 합니다.</p> - -<h4>알림과 작업 연결하기</h4> - -<p>휴대폰과 같이 연결된 기기는 알림을 Wear 기기에 연결하여 해당 기기에서 -알림이 표시될 수 있게 합니다. 마찬가지로 작업도 연결할 수 있기 때문에 사용자는 Wear 기기에서 -알림을 바로 처리할 수 있습니다.</p> - -<p><strong>연결해야 할 사항</strong></p> - -<ul> - <li> 새 인스턴트 메시지</li> - <li> +1, Like, Heart와 같은 단일 탭 작업</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/WearBasic.png" width="156px" height="156px" alt="" /> - -<p><strong>연결하지 않아야 할 사항</strong></p> - -<ul> - <li> 새로 도착한 팟캐스트의 알림</li> - <li> 워치에서 수행할 수 없는 기능에 매핑되는 작업</li> -</ul> - - - -<p><h4>Wear에 대해서만 정의할 수 있는 고유한 작업</h4></p> - -<p>Wear에서만 수행할 수 있는 작업이 몇 가지 있으며, 이러한 작업은 다음과 같습니다.</p> - -<ul> - <li> "금방 올게"와 같은 미리 준비된 대답으로 구성된 빠른 목록</li> - <li> 휴대폰에서 열기</li> - <li> 음성 입력 화면을 불러오는 "댓글 달기" 또는 "응답" 작업</li> - <li> Wear에 특화된 앱을 실행하는 작업</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/ReplyAction.png" width="156px" height="156px" alt="" /> diff --git a/docs/html-intl/intl/pt-br/design/patterns/notifications.jd b/docs/html-intl/intl/pt-br/design/patterns/notifications.jd deleted file mode 100644 index 5560e85f5c2e..000000000000 --- a/docs/html-intl/intl/pt-br/design/patterns/notifications.jd +++ /dev/null @@ -1,872 +0,0 @@ -page.title=Notificações -page.tags="notifications","design","L" -@jd:body - - <a class="notice-developers" href="{@docRoot}training/notify-user/index.html"> - <div> - <h3>Documentos do desenvolvedor</h3> - <p>Notificação ao usuário</p> - </div> -</a> - -<a class="notice-designers" href="notifications_k.html"> - <div> - <h3>Notificações no Android 4.4 e em anteriores</h3> - </div> -</a> - -<!-- video box --> -<a class="notice-developers-video" href="https://www.youtube.com/watch?v=Uiq2kZ2JHVY"> -<div> - <h3>Vídeo</h3> - <p>DevBytes: Notificações na pré-visualização do desenvolvedor do Android L</p> -</div> -</a> - -<style> - .col-5, .col-6, .col-7 { - margin-left:0px; - } -</style> - -<p>O sistema de notificações permite que os usuários se mantenham informados sobre eventos relevantes e -imediatos -no aplicativo, como novas mensagens de bate-papo de um amigo ou um evento de calendário. -Pense nas notificações como um canal de notícias que alerta o usuário sobre eventos -importantes à -medida que acontecem ou sobre um registro que grava eventos enquanto o usuário não está prestando -atenção — e que é sincronizado conforme apropriado em todos os dispositivos Android dele.</p> - -<h4 id="New"><strong>Novo no Android 5.0</strong></h4> - -<p>No Android 5.0, as notificações recebem atualizações importantes: em termos estruturais, visuais e -funcionais:</p> - -<ul> - <li>As notificações passaram por mudanças visuais consistentes com o novo -tema do Material Design.</li> - <li> As notificações agora estão disponíveis na tela de bloqueio do dispositivo, enquanto que -o conteúdo sensível ainda pode -ficar oculto atrás dela.</li> - <li>Notificações de alta prioridade recebidas enquanto o dispositivo está em uso agora usam um novo formato, chamado de -notificações heads-up.</li> - <li>Notificações sincronizadas na nuvem: descartar uma notificação em um dos -dispositivos Android a descarta -também nos outros.</li> -</ul> - -<p class="note"><strong>Observação:</strong> o projeto de notificação nesta versão do -Android é uma mudança -significativa em relação às versões anteriores. Para obter informações sobre o projeto de notificação em versões -anteriores, consulte <a href="./notifications_k.html">Notificações no Android 4.4 ou em anteriores</a>.</p> - -<h2 id="Anatomy">Anatomia de uma notificação</h2> - -<p>Esta seção aborda as partes básicas de uma notificação e como elas -podem aparecer em diferentes tipos de dispositivos.</p> - -<h3 id="BaseLayout">Layout básico</h3> - -<p>No mínimo, todas as notificações consistem em um layout básico, incluindo:</p> - -<ul> - <li> O <strong>ícone</strong> da notificação. O ícone simboliza o -aplicativo de origem. Ele também - pode indicar o tipo de notificação, caso o aplicativo gere mais de um -tipo.</li> - <li> Um <strong>título</strong> da notificação e -<strong>texto</strong> adicional.</li> - <li> Uma <strong>marcação de data e hora</strong>.</li> -</ul> - -<p>Notificações criadas com {@link android.app.Notification.Builder Notification.Builder} -para versões anteriores da plataforma têm a mesma aparência e o mesmo funcionamento no Android -5.0, com apenas mudanças menores de estilo que o sistema -entrega a você. Para obter mais informações sobre notificações em versões -anteriores do Android, consulte -<a href="./notifications_k.html">Notificações no Android 4.4 ou em anteriores</a>.</p></p> - - - <img style="margin:20px 0 0 0" src="{@docRoot}images/android-5.0/notifications/basic_combo.png" alt="" width="700px" /> - - -<div style="clear:both;margin-top:20px"> - <p class="img-caption"> - Layout básico de uma notificação em dispositivo portátil (à esquerda) e a mesma notificação em Wear (à direita), -com uma foto do usuário e um ícone de notificação - </p> - </div> - -<h3 id="ExpandedLayouts">Layouts expandidos</h3> - - -<p>Você pode escolher o nível de detalhe que as notificações de seu aplicativo -devem fornecer. Elas podem mostrar as primeiras -linhas de uma mensagem ou exibir uma visualização de imagem maior. As informações -adicionais fornecem ao usuário mais -contexto e — em alguns casos — podem permitir que o usuário leia uma mensagem -em sua totalidade. O usuário pode -pinçar para aproximar ou afastar a vista ou realizar deslizamento de um dedo para alternar entre os layouts -compacto e expandido. - Para notificações de um evento, o Android fornece três modelos de layout -expandido (texto, caixa de entrada e - imagem) para usar em seu aplicativo. As imagens a seguir mostram como -se parecem notificações de um evento em - dispositivos portáteis (à esquerda) e usados junto ao corpo (à direita).</p> - -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/expandedtext_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/stack_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/ExpandedImage.png" - alt="" width="311px" height;="450px" /> - -<h3 id="actions" style="clear:both; margin-top:40px">Ações</h3> - -<p>O Android tem suporte para ações opcionais que são exibidas na parte inferior -da notificação. -Com ações, os usuários podem tratar as tarefas mais comuns para -determinada notificação de dentro da sombra da notificação sem precisar abrir o -aplicativo de origem. -Isso acelera a interação e, em conjunto com deslizar-para-descartar, ajuda os usuários a -se concentrarem em notificações que sejam importantes.</p> - - - <img src="{@docRoot}images/android-5.0/notifications/action_combo.png" alt="" width="700px" /> - - - -<p style="clear:both">Tenha cuidado com o número de ações que inclui em uma -notificação. Quanto mais -ações incluir, maior será a complexidade cognitiva criada. Limite-se -ao menor número possível -de ações, incluindo apenas as ações efetivamente mais importantes e -significativas.</p> - -<p>Boas candidatas a ações em notificações são ações que:</p> - -<ul> - <li> Sejam essenciais, frequentes e típicas para o tipo de conteúdo -exibido - <li> Permitam que o usuário realize tarefas rapidamente -</ul> - -<p>Evite ações que sejam:</p> - -<ul> - <li> Ambíguas - <li> Idênticas à ação padrão da notificação (como "Ler" ou -"Abrir") -</ul> - - - -<p>Você pode especificar no máximo três ações, cada uma consistindo em um ícone -e um nome de ação. - Adicionar ações a um layout básico simples torna a notificação expansível, -mesmo se a -notificação não tiver um layout expandido. Como as ações são exibidas apenas para notificações -expandidas - e que ficam de outra forma ocultas, certifique-se de que qualquer ação que um -usuário possa invocar de dentro de uma - notificação esteja disponível também dentro do aplicativo -associado.</p> - -<h2 style="clear:left">Notificação heads-up</h2> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/hun-example.png" alt="" width="311px" /> - <p class="img-caption"> - Exemplo de uma notificação heads-up (chamada telefônica recebida, alta prioridade) -que aparece sobre um -aplicativo imersivo - </p> -</div> - -<p>Quando uma notificação de alta prioridade chega (veja à direita), ela é apresentada -aos usuários por -um período curto com um layout expandido mostrando possíveis ações.</p> -<p> Depois desse período, a notificação recua para a sombra -de notificação. Se a <a href="#correctly_set_and_manage_notification_priority">prioridade</a> de uma notificação for -marcada como Alta, Máxima ou tela cheia, ela receberá uma notificação heads-up.</p> - -<p><b>Bons exemplos de notificações heads-up</b></p> - -<ul> - <li> Chamada telefônica recebida durante o uso do dispositivo</li> - <li> Alarme durante o uso do dispositivo</li> - <li> Nova mensagem SMS</li> - <li> Bateria fraca</li> -</ul> - -<h2 style="clear:both" id="guidelines">Diretrizes</h2> - - -<h3 id="MakeItPersonal">Torne-a pessoal</h3> - -<p>Para notificações de itens enviados por outra pessoa (como uma mensagem ou -atualização de status), inclua a imagem da pessoa usando -{@link android.app.Notification.Builder#setLargeIcon setLargeIcon()}. Anexe também informações sobre -a pessoa nos metadados da notificação (consulte {@link android.app.Notification#EXTRA_PEOPLE}).</p> - -<p>O ícone principal de sua notificação ainda é mostrado, portanto, o usuário pode associá-lo -ao ícone -visível na barra de status.</p> - - -<img src="{@docRoot}images/android-5.0/notifications/Triggered.png" alt="" width="311px" /> -<p style="margin-top:10px" class="img-caption"> - Notificação que mostra a pessoa que a ativou e o conteúdo enviado. -</p> - - -<h3 id="navigate_to_the_right_place">Navegação para o lugar certo</h3> - -<p>Quando o usuário toca no corpo de uma notificação (fora dos botões -de ação), abra o aplicativo -no lugar em que o usuário possa visualizar e agir sobre os dados referenciados na -notificação. Na maioria dos casos, será a exibição detalhada de um único item de dado, como uma mensagem, -mas também poderá ser uma -vista resumida se a notificação estiver empilhada. Se o aplicativo -levar o usuário a qualquer lugar abaixo do nível superior do aplicativo, insira a navegação na pilha de retorno do aplicativo para que -o usuário possa pressionar o botão Voltar do sistema para voltar ao nível superior. Para obter mais informações, consulte -<em>Navegação para o seu aplicativo pelos widgets de página inicial e notificações</em> no padrão de projeto de <a href="{@docRoot}design/patterns/navigation.html#into-your-app">Navegação</a>. -</p> - -<h3 id="correctly_set_and_manage_notification_priority">Definição e gerenciamento -corretos da prioridade das -notificações</h3> - -<p>O Android tem suporte para um sinalizador de prioridade para notificações. Esse sinalizador permite -influenciar o local em que a notificação é exibida em relação a outras notificações e -ajuda a garantir -que os usuários sempre vejam primeiro as notificações mais importantes. Você pode escolher entre -os seguintes -níveis de prioridade ao publicar uma notificação:</p> -<table> - <tr> - <td class="tab0"> -<p><strong>Prioridade</strong></p> -</td> - <td class="tab0"> -<p><strong>Uso</strong></p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MAX</code></p> -</td> - <td class="tab1"> -<p>Use para notificações críticas e urgentes que alertam o usuário sobre uma condição -que depende -do tempo ou que precisa ser resolvida antes que o usuário possa continuar -com uma determinada tarefa.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>HIGH</code></p> -</td> - <td class="tab1"> -<p>Use principalmente para comunicações importantes, como uma mensagem ou -eventos de bate-papo com conteúdo particularmente interessante para o usuário. -Notificações de alta prioridade acionam a exibição de uma notificação heads-up.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>DEFAULT</code></p> -</td> - <td class="tab1"> -<p>Use para todas as notificações que não recaiam em nenhuma das outras prioridades descritas aqui.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>LOW</code></p> -</td> - <td class="tab1"> -<p>Use para notificações sobre as quais deseja que o usuário seja informado, mas -que sejam menos urgentes. Notificações de baixa prioridade tendem a ser exibidas na parte inferior da lista, -o que as torna uma boa -opção para coisas como atualizações públicas ou sociais não direcionadas: o usuário pediu para -ser notificado sobre -elas, mas essas notificações nunca devem ter precedência sobre comunicações -urgentes ou diretas.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MIN</code></p> -</td> - <td class="tab1"> -<p>Use para informações contextuais ou de histórico, como informações sobre clima ou -informações contextuais de localização. -Notificações de prioridade mínima não aparecem na barra de status. O usuário -as descobre expandindo a sombra da notificação.</p> -</td> - </tr> -</table> - - -<h4 id="how_to_choose_an_appropriate_priority"><strong>Como escolher uma prioridade -adequada -</strong></h4> - -<p><code>DEFAULT</code>, <code>HIGH</code> e <code>MAX</code> são níveis de prioridade de interrupção e arriscam -interromper a atividade -do usuário. Para evitar irritar os usuários de seu aplicativo, reserve níveis de prioridade de interrupção para -notificações que:</p> - -<ul> - <li> Envolvam outra pessoa</li> - <li> Dependam do tempo</li> - <li> Possam mudar imediatamente o comportamento do usuário no mundo real</li> -</ul> - -<p>Notificações definidas como <code>LOW</code> e <code>MIN</code> ainda podem -ser valiosas para o usuário: muitas, se não a maioria, das notificações não precisam demandar a atenção -imediata do usuário, ou vibrar o pulso do usuário, mas ainda contêm informações que o usuário -achará valiosas ao decidir procurar -notificações. Os critérios para notificações de prioridade <code>LOW</code> e <code>MIN</code> -incluem:</p> - -<ul> - <li> Não envolver outras pessoas</li> - <li> Não depender de tempo</li> - <li> Ter conteúdo no qual o usuário pode estar interessado, mas que pode decidir -verificar no momento em que desejar</li> -</ul> - - - <img src="{@docRoot}images/android-5.0/notifications/notifications_pattern_priority.png" alt="" width="700" /> - - -<h3 style="clear:both" id="set_a_notification_category">Definição de uma categoria -de notificação</h3> - -<p>Se a sua notificação recair em uma das categorias predefinidas (veja -abaixo), atribua-a -adequadamente. Aspectos da IU do sistema, como a sombra da notificação (ou qualquer -outra escuta -de notificação), podem usar essas informações para tomar decisões de classificação e filtragem.</p> -<table> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_CALL">CATEGORY_CALL</a></code></p> -</td> - <td> -<p>Chamada recebida (voz ou vídeo) ou solicitação similar de -comunicação síncrona</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_MESSAGE">CATEGORY_MESSAGE</a></code></p> -</td> - <td> -<p>Mensagem direta recebida (SMS, mensagem instantânea etc.)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EMAIL">CATEGORY_EMAIL</a></code></p> -</td> - <td> -<p>Mensagens assíncronas em lote (e-mail)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EVENT">CATEGORY_EVENT</a></code></p> -</td> - <td> -<p>Evento de calendário</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROMO">CATEGORY_PROMO</a></code></p> -</td> - <td> -<p>Promoção ou publicidade</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ALARM">CATEGORY_ALARM</a></code></p> -</td> - <td> -<p>Alarme ou cronômetro</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROGRESS">CATEGORY_PROGRESS</a></code></p> -</td> - <td> -<p>Andamento de uma operação de execução longa em segundo plano</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SOCIAL">CATEGORY_SOCIAL</a></code></p> -</td> - <td> -<p>Atualização de rede social ou de compartilhamento</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ERROR">CATEGORY_ERROR</a></code></p> -</td> - <td> -<p>Erro em operação de segundo plano ou no status de autenticação</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_TRANSPORT">CATEGORY_TRANSPORT</a></code></p> -</td> - <td> -<p>Controle de transporte de mídia para reprodução</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SYSTEM">CATEGORY_SYSTEM</a></code></p> -</td> - <td> -<p>Atualização do sistema ou do status do dispositivo. Reservado para uso do sistema.</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SERVICE">CATEGORY_SERVICE</a></code></p> -</td> - <td> -<p>Indicação de serviço de segundo plano em execução</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_RECOMMENDATION">CATEGORY_RECOMMENDATION</a></code></p> -</td> - <td> -<p>Uma recomendação específica e oportuna para uma única coisa. Por exemplo, um aplicativo -de notícias pode querer -recomendar uma notícia que acredita que o usuário desejará ler em seguida.</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_STATUS">CATEGORY_STATUS</a></code></p> -</td> - <td> -<p>Informações contínuas sobre o dispositivo ou o status contextual</p> -</td> - </tr> -</table> - -<h3 id="summarize_your_notifications">Resuma as notificações</h3> - -<p>Se uma notificação de um certo tipo já estiver pendente quando o aplicativo tentar enviar uma nova -notificação do mesmo tipo, combine-as em uma única notificação de resumo para o aplicativo. Não -crie um novo objeto.</p> - -<p>Uma notificação de resumo cria uma descrição resumida e permite que o -usuário entenda quantas notificações -de um determinado tipo estão pendentes.</p> - -<div class="col-6"> - -<p><strong>O que não fazer</strong></p> - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Dont.png" alt="" width="311px" /> -</div> - -<div> -<p><strong>O que fazer</strong></p> - - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Do.png" alt="" width="311px" /> -</div> - -<p style="clear:left; padding-top:30px; padding-bottom:20px">Você pode fornecer -mais detalhes sobre as notificações individuais que compõem um -resumo usando o layout resumido expandido. Essa abordagem permite que os usuários -entendam melhor quais -notificações estão pendentes e decidam se estão interessados o suficiente para lê-las -em detalhes dentro -do aplicativo associado.</p> -<div class="col-6"> - <img src="{@docRoot}images/android-5.0/notifications/Stack.png" style="margin-bottom:20px" alt="" width="311px" /> - <p class="img-caption"> - Notificação expandida e contraída que é um resumo (usando <code>InboxStyle</code>) - </p> -</div> - -<h3 style="clear:both" id="make_notifications_optional">Torne as notificações -opcionais</h3> - -<p>Os usuários devem sempre controlar as notificações. Permita que o usuário -desative as notificações -de seu aplicativo ou altere as propriedades de alerta, como som de alerta e -se a vibração será usada, -adicionando um item de configuração da notificação nas configurações do aplicativo.</p> - -<h3 id="use_distinct_icons">Use ícones distintos</h3> -<p>Ao olhar para a área de notificação, o usuário deverá ser capaz de discernir -que tipos de -notificações estão atualmente pendentes.</p> - -<div class="figure"> - <img src="{@docRoot}images/android-5.0/notifications/ProductIcons.png" alt="" width="420" /> -</div> - - <div><p><strong>O que fazer</strong></p> - <p>Verifique os ícones de notificação que os aplicativos do Android já fornecem e crie -ícones de notificação para o seu -aplicativo que tenham aparência suficientemente distinta.</p> - - <p><strong>O que fazer</strong></p> - <p>Use o <a href="/design/style/iconography.html#notification">estilo de ícone de notificação</a> apropriado - para ícones pequenos e o - <a href="/design/style/iconography.html#action-bar">estilo de ícone de barra -de ação</a> da luminosidade do Material para os ícones - de ação.</p> -<p ><strong>O que fazer</strong></p> -<p >Mantenha os ícones visualmente simples, evitando detalhes excessivos que sejam -difíceis de discernir.</p> - - <div><p><strong>O que não fazer</strong></p> - <p>Coloque um alfa adicional (esmaecimento ou redução de intensidade) nos ícones pequenos -e nos ícones de - ação; eles podem ter bordas suavizadas, mas, como o Android usa esses -ícones como máscaras (ou seja, somente - o canal alfa é usado), a imagem normalmente deve ser desenhada com -opacidade total.</p> - -</div> -<p style="clear:both"><strong>O que não fazer</strong></p> - -<p>Use cores para distinguir o seu aplicativo dos outros. Ícones de notificação devem -somente ser uma imagem com fundo branco sobre transparente.</p> - - -<h3 id="pulse_the_notification_led_appropriately">Pisque o LED de notificação -adequadamente</h3> - -<p>Muitos dispositivos Android contêm um LED de notificação, que é usado para manter o -usuário informado sobre -eventos enquanto a tela está desligada. Notificações com um nível de prioridade de <code>MAX</code>, -<code>HIGH</code> ou <code>DEFAULT</code> devem -fazer com que o LED brilhe, enquanto que os de prioridade mais baixa (<code>LOW</code> e -<code>MIN</code>) não devem.</p> - -<p>O controle do usuário sobre as notificações deve se estender ao LED. Ao usar -DEFAULT_LIGHTS, o -LED brilhará na cor branca. Suas notificações não devem usar uma cor -diferente, a não ser que o -usuário as tenha explicitamente personalizado.</p> - -<h2 id="building_notifications_that_users_care_about">Criação de notificações -que agradam aos usuários</h2> - -<p>Para criar um aplicativo que os usuários amem, é importante projetar as -notificações cuidadosamente. -As notificações personificam a voz do seu aplicativo e contribuem para -a personalidade dele. Notificações indesejadas ou -irrelevantes podem irritar o usuário ou fazer com que ele reprove a -quantidade de atenção que o -aplicativo exige. Portanto, use notificações de forma cuidadosa.</p> - -<h3 id="when_to_display_a_notification">Quando exibir uma notificação</h3> - -<p>Para criar um aplicativo que as pessoas gostem de usar, é importante -reconhecer que a atenção e o foco -do usuário são recursos que devem ser protegidos. Apesar de o sistema de -notificação do Android ter -sido projetado para minimizar o impacto das notificações na atenção do usuário, -ainda é -importante ter ciência do fato de que as notificações interrompem o -fluxo de tarefas do usuário. -Ao planejar as notificações, pergunte-se se elas são importantes o suficiente para -justificar uma interrupção. Se não tiver certeza, permita que o usuário decida se quer -uma notificação usando as configurações de notificação do seu aplicativo ou ajuste -o sinalizador de prioridade das notificações para <code>LOW</code> ou <code>MIN</code> para -evitar distrair o usuário enquanto ele faz -alguma outra coisa.</p> - - <img src="{@docRoot}images/android-5.0/notifications/TimeSensitive.png" alt="" width="311px" /> - <p style="margin-top:10px" class="img-caption"> - Exemplos de notificação que depende de tempo - </p> - -<p>Apesar de aplicativos bem comportados geralmente se manifestarem apenas quando ocorre interação com eles, alguns -casos justificam que o aplicativo interrompa o usuário com uma notificação não solicitada.</p> - -<p>Use notificações principalmente para <strong>eventos que dependam de tempo</strong>, especialmente - se esses eventos síncronos <strong>envolverem outras pessoas</strong>. Por -exemplo, um bate-papo recebido -é uma forma síncrona em tempo real de comunicação: outro usuário -espera ativamente a resposta. Eventos de calendário são outro exemplo bom de quando usar uma -notificação e atrair a -atenção do usuário, pois o evento é iminente e eventos de calendário frequentemente -envolvem outras pessoas.</p> - -<h3 style="clear:both" id="when_not_to_display_a_notification">Quando não exibir -uma notificação</h3> - -<div class="figure" style="margin-top:60px"> - <img src="{@docRoot}images/android-5.0/notifications/AntiSample1.png" alt="" width="311px" /> -</div> - -<p>Em muitos outros casos, notificações não são adequadas:</p> - -<ul> - <li> Evite notificar o usuário sobre informações que não são especificamente -direcionadas a ele ou -que não dependam realmente de tempo. Por exemplo, as atualizações -assíncronas e não direcionadas -que fluem por uma rede social geralmente não justificam uma interrupção -em tempo real. Para os usuários que se importam -com elas, deixe que decidam recebê-las.</li> - <li> Não crie uma notificação se as informações novas relevantes estiverem -atualmente na tela. Em vez disso, -use a IU do próprio aplicativo para notificar o usuário das novas informações -diretamente no contexto. - Por exemplo, um aplicativo de bate-papo não deve criar notificações de sistema enquanto o -usuário estiver conversando ativamente com outro usuário.</li> - <li> Não interrompa o usuário para realizar operações técnicas de baixo nível, como salvar -ou sincronizar informações, nem atualize um aplicativo se o aplicativo ou o sistema puder resolver -o problema sem envolver o usuário.</li> - <li> Não interrompa o usuário para informar um erro se o aplicativo -puder se recuperar dele por conta própria, sem que o usuário -tome qualquer ação.</li> - <li> Não crie notificações que não tenham conteúdo real de notificação e -que meramente anunciem o seu -aplicativo. Uma notificação deve fornecer informações úteis, oportunas e novas e -não deve ser usada -meramente para executar um aplicativo.</li> - <li> Não crie notificações supérfluas apenas para colocar sua marca na frente -dos usuários. - Tais notificações frustram e provavelmente alienam seu público-alvo. A -melhor forma de fornecer - pequenas quantidades de informações atualizadas e manter o usuário envolvido -com o seu - aplicativo é desenvolver um widget que ele possa colocar na -tela inicial.</li> -</ul> - -<h2 style="clear:left" id="interacting_with_notifications">Interação com -notificações</h2> - -<p>Notificações são indicadas por ícones na barra de status e podem ser acessadas -abrindo a -gaveta de notificações.</p> - -<p>Tocar em uma notificação abre o aplicativo associado com o conteúdo -detalhado que corresponde à notificação. -Deslizar à esquerda ou à direita em uma notificação a remove da gaveta.</p> - -<h3 id="ongoing_notifications">Notificações contínuas</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/MusicPlayback.png" alt="" width="311px" /> - <p class="img-caption"> - Notificação contínua devido à reprodução de música - </p> -</div> -<p>Notificações contínuas mantêm os usuários informados sobre um processo em andamento em -segundo plano. -Por exemplo, reprodutores de música anunciam a faixa em reprodução no -sistema de notificação e -continuam a fazer isso até que o usuário interrompa a reprodução. Notificações contínuas também podem -mostrar ao usuário -feedback sobre tarefas mais longas, como o download de um arquivo ou a codificação de um vídeo. Um usuário não pode remover -manualmente uma notificação contínua da gaveta de notificações.</p> - -<h3 id="ongoing_notifications">Reprodução de mídia</h3> -<p>No Android 5.0, a tela de bloqueio não mostra controles de transporte por causa da classe -{@link android.media.RemoteControlClient} obsoleta. Mas ela <em>mostra</em> notificações, portanto, a notificação de reprodução -de cada aplicativo agora é a forma -principal para que os usuários controlem a reprodução em um estado bloqueado. Esse comportamento dá aos aplicativos mais -controle sobre quais -botões exibir e de que forma, ao mesmo tempo em que fornece uma experiência consistente -para o usuário, com a tela bloqueada ou não.</p> - -<h3 style="clear:both" -id="dialogs_and_toasts_are_for_feedback_not_notification">Diálogos -e avisos</h3> - -<p>O seu aplicativo não deve criar uma caixa de diálogo ou um aviso se não estiver -atualmente na tela. Uma caixa de diálogo ou um aviso - deve ser exibido somente como uma resposta imediata ao usuário tomando uma ação -dentro do seu aplicativo. -Para obter orientação adicional sobre o uso de caixas de diálogo e avisos, consulte -<a href="/design/patterns/confirming-acknowledging.html">Confirmação e reconhecimento</a>.</p> - -<h3>Avaliação e classificação</h3> - -<p>Notificações são notícias e, portanto, são essencialmente exibidas -em ordem cronológica inversa, com -consideração especial para a -<a href="#correctly_set_and_manage_notification_priority">prioridade</a> da notificação declarada no aplicativo.</p> - -<p>Notificações são uma parte importante da tela de bloqueio e são exibidas proeminentemente -sempre -que a tela do dispositivo é exibida. O espaço na tela de bloqueio é restrito, portanto, -é mais importante -do que nunca identificar as notificações mais urgentes ou relevantes. Por esse -motivo, o Android tem um -algoritmo de classificação mais sofisticado para notificações, levando em conta:</p> - -<ul> - <li> A marcação de data e hora e a prioridade declarada no aplicativo.</li> - <li> Se a notificação incomodou recentemente o usuário com som ou -vibração (ou seja, - se o celular acabou de fazer um ruído e o usuário deseja saber "O que acabou de -acontecer?", a tela de bloqueio - deve responder com um olhar rápido).</li> - <li> Qualquer pessoa anexada à notificação usando {@link android.app.Notification#EXTRA_PEOPLE} - e, em particular, se é contato especial (com estrelas).</li> -</ul> - -<p>Para aproveitar ao máximo essa classificação, concentre-se na experiência -do usuário que deseja -criar, e não em um determinado local na lista.</p> - - <img src="{@docRoot}images/android-5.0/notifications/AntiSample3.png" alt="" width="700px" /> - - <p class="img-caption" style="margin-top:10px">Notificações do Gmail têm -prioridade padrão e normalmente - são classificadas abaixo de mensagens de um aplicativo de mensagem instantânea, como o Hangouts, mas -recebem - uma promoção temporária quando novas mensagens chegam. - </p> - - -<h3>Na tela de bloqueio</h3> - -<p>Como as notificações são visíveis na tela de bloqueio, a privacidade do usuário é uma consideração -especialmente - importante. Notificações frequentemente contêm informações sensíveis e -não devem necessariamente estar visíveis -para qualquer pessoa que ligar a tela do dispositivo.</p> - -<ul> - <li> Para dispositivos que têm uma tela de bloqueio segura (PIN, padrão ou senha), a interface tem -partes públicas e privadas. A interface pública pode ser exibida em uma tela de bloqueio segura e, -portanto, vista por qualquer pessoa. A interface privada é o mundo atrás da tela de bloqueio e -só é revelada depois que o usuário faz login no dispositivo.</li> -</ul> - -<h3>Controle do usuário sobre as informações exibidas na tela de bloqueio segura</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/LockScreen@2x.png" srcset="{@docRoot}images/android-5.0/notifications/LockScreen.png 1x" alt="" width="311px" /> - <p class="img-caption"> - Notificações na tela de bloqueio com conteúdo revelado depois que o usuário desbloqueia o dispositivo. - </p> -</div> - -<p>Ao definir uma tela de bloqueio segura, o usuário poderá escolher ocultar -detalhes sensíveis da tela de bloqueio segura. Nesse caso, a IU do sistema -considerará o <em>nível de visibilidade</em> da notificação para descobrir o que pode -ser exibido com segurança.</p> -<p> Para controlar o nível de visibilidade, chame -<code><a -href="/reference/android/app/Notification.Builder.html#setVisibility(int)">Notification.Builder.setVisibility()</a></code> -e especifique um destes valores:</p> - -<ul> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PUBLIC">VISIBILITY_PUBLIC</a></code>. -Exibe o conteúdo inteiro da notificação. - Esse é o padrão do sistema se a visibilidade não for especificada.</li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PRIVATE">VISIBILITY_PRIVATE</a></code>. -Na tela de bloqueio, exibe informações básicas sobre essa notificação, incluindo o -ícone e o nome do aplicativo que a publicou. O restante dos detalhes da notificação não é exibido. -Alguns pontos a ter em mente são: - <ul> - <li> Se você quer fornecer uma versão pública diferente da sua notificação -para que o sistema a exiba em uma tela de bloqueio segura, forneça um objeto -Notificação substituto no campo <code><a -href="/reference/android/app/Notification.html#publicVersion">Notification.publicVersion</a></code>. - - <li> Essa configuração dá ao aplicativo uma oportunidade de criar uma versão alternativa do -conteúdo que ainda é útil, mas não revela informações pessoais. Considere o exemplo de um -aplicativo de SMS cujas notificações incluem o texto da mensagem SMS, o nome do remetente e o ícone do contato. -Essa notificação deve ser <code>VISIBILITY_PRIVATE</code>, mas <code>publicVersion</code> ainda pode -conter informações úteis, como "3 novas mensagens", sem outros detalhes -de identificação. - </ul> - </li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_SECRET">Notification.VISIBILITY_SECRET</a></code>. Mostra apenas as informações mínimas, excluindo até mesmo -o ícone da notificação.</li> -</ul> -<h2 style="clear:both" id="notifications_on_android_wear">Notificações no -Android Wear</h2> - -<p>Notificações e suas <em>ações</em> são enviadas a dispositivos Wear por padrão. -Os desenvolvedores podem controlar que notificações são enviadas do -celular ao relógio -e vice-versa. Os desenvolvedores também podem controlar quais ações são transmitidas. Se o -seu aplicativo inclui -ações que não podem ser executadas com um toque, oculte essas ações -na sua notificação do Wear -ou considere colocá-las em um aplicativo do Wear, permitindo que o usuário -termine a ação -no relógio.</p> - -<h4>Transmissão de notificações e ações</h4> - -<p>Um dispositivo conectado, como um celular, pode transmitir notificações para um dispositivo Wear para que as -notificações sejam exibidas nele. De forma similar, ele pode transmitir ações para que o usuário possa agir -sobre as notificações diretamente do dispositivo Wear.</p> - -<p><strong>Transmitir</strong></p> - -<ul> - <li> Novas mensagens instantâneas</li> - <li> Ações de um toque, como +1, Curtir, Coração</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/WearBasic.png" width="156px" height="156px" alt="" /> - -<p><strong>Não transmitir</strong></p> - -<ul> - <li> Notificações de podcasts recém-chegados</li> - <li> Ações que mapeiem para recursos que não são possíveis no relógio</li> -</ul> - - - -<p><h4>Ações exclusivas a definir para Wear</h4></p> - -<p>Há algumas ações que só podem ser realizadas em Wear. Elas incluem:</p> - -<ul> - <li> Listas rápidas de respostas prontas, como "Volto logo"</li> - <li> Abrir no celular</li> - <li> Uma ação "Comentar" ou "Responder" que abre a tela de entrada de voz</li> - <li> Ações que executam aplicativos específicos de Wear</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/ReplyAction.png" width="156px" height="156px" alt="" /> diff --git a/docs/html-intl/intl/ru/design/patterns/notifications.jd b/docs/html-intl/intl/ru/design/patterns/notifications.jd deleted file mode 100644 index 4d339c29258d..000000000000 --- a/docs/html-intl/intl/ru/design/patterns/notifications.jd +++ /dev/null @@ -1,872 +0,0 @@ -page.title=Уведомления -page.tags="notifications","design","L" -@jd:body - - <a class="notice-developers" href="{@docRoot}training/notify-user/index.html"> - <div> - <h3>Документация для разработчиков</h3> - <p>Уведомление пользователя</p> - </div> -</a> - -<a class="notice-designers" href="notifications_k.html"> - <div> - <h3>Уведомления в Android версии 4.4 и ниже</h3> - </div> -</a> - -<!-- video box --> -<a class="notice-developers-video" href="https://www.youtube.com/watch?v=Uiq2kZ2JHVY"> -<div> - <h3>Видеоролик</h3> - <p>DevBytes: Уведомления в Android L Developer Preview</p> -</div> -</a> - -<style> - .col-5, .col-6, .col-7 { - margin-left:0px; - } -</style> - -<p>Уведомления позволяют извещать пользователя о релевантных и -периодически возникающих -событиях в приложении, таких как новые сообщения в чате или события в календаре. -Систему уведомлений можно рассматривать как канал новостей, извещающий пользователя о важных -событиях по мере -их возникновения, или как журнал, ведущий хронику событий, пока пользователь не обращает на них -внимания, и синхронизируемый должным образом на всех устройствах Android этого пользователя.</p> - -<h4 id="New"><strong>Новые возможности Android 5.0</strong></h4> - -<p>В Android 5.0 уведомления были существенно обновлены структурно, -визуально, и функционально:</p> - -<ul> - <li>был изменен внешний вид уведомлений в соответствии с новой -темой Material Design;</li> - <li> теперь уведомления доступны на экране блокировки, в то время как -конфиденциальная информация по-прежнему - может быть скрыта;</li> - <li>уведомления с высоким приоритетом, полученные при включенном устройстве, теперь имеют новый формат и называются - уведомлениями Heads-up;</li> - <li>уведомления синхронизируются с облаком: если удалить уведомление на одном из устройств -Android, оно будет удалено - и на остальных устройствах.</li> -</ul> - -<p class="note"><strong>Примечание.</strong> Разработка уведомлений в этой версии -Android значительно -отличается от их разработки в предыдущих версиях. Информацию о разработке уведомлений в предыдущих -версиях можно найти в разделе <a href="./notifications_k.html">Уведомления в Android версии 4.4 и ниже</a>.</p> - -<h2 id="Anatomy">Структура уведомления</h2> - -<p>В этом разделе описываются основные компоненты уведомления и их -отображение на устройствах различных типов.</p> - -<h3 id="BaseLayout">Базовая компоновка</h3> - -<p>Все уведомления имеют, как минимум, базовую компоновку, которую составляют следующие элементы.</p> - -<ul> - <li> <strong>Значок</strong> уведомления. Значок символизирует -инициирующее приложение. Он также может - указывать на тип уведомления, если приложение генерирует уведомления нескольких -типов.</li> - <li> <strong>Заголовок</strong> уведомления и дополнительный -<strong>текст</strong>.</li> - <li> <strong>Временная метка</strong>.</li> -</ul> - -<p>Уведомления, созданные с помощью {@link android.app.Notification.Builder Notification.Builder} -для предыдущих версий платформы, выглядят и функционируют в Android -5.0 так же, как и прежде, за исключением незначительных стилистических отличий, вносимых -системой. Дополнительную информацию о внешнем виде и функциональности уведомлений в предыдущих версиях -Android можно найти в разделе -<a href="./notifications_k.html">Уведомления в Android версии 4.4 и ниже</a>.</p></p> - - - <img style="margin:20px 0 0 0" src="{@docRoot}images/android-5.0/notifications/basic_combo.png" alt="" width="700px" /> - - -<div style="clear:both;margin-top:20px"> - <p class="img-caption"> - Уведомление в базовой компоновке на мобильном устройстве (слева) и то же уведомление на носимом устройстве (справа) - с фотографией пользователя и значком уведомления - </p> - </div> - -<h3 id="ExpandedLayouts">Расширенная компоновка</h3> - - -<p>Разработчик может выбрать степень подробности уведомлений, генерируемых его -приложением. Уведомление может содержать первые -несколько строк сообщения или миниатюру изображения. В качестве дополнительной -информации можно предоставлять пользователю -контекст и, —в некоторых случаях, —давать ему возможность прочитать сообщение -целиком. Чтобы переключаться - между компактной и расширенной компоновкой, пользователь может применить жест сжатия/масштабирования или -провести пальцем по экрану. - Для уведомлений о единичных событиях Android предоставляет - разработчику приложения три шаблона расширенной компоновки -(текст, входящая почта и изображения). Ниже приведены скриншоты уведомлений о единичных -событиях на мобильных устройствах (слева) - и на носимых устройствах (справа).</p> - -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/expandedtext_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/stack_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/ExpandedImage.png" - alt="" width="311px" height;="450px" /> - -<h3 id="actions" style="clear:both; margin-top:40px">Действия</h3> - -<p>Android поддерживает дополнительные действия, отображаемые в нижней части -уведомления. -Благодаря этому пользователи могут выполнять операции, типичные для данного -уведомления, непосредственно из него, не открывая -само приложение. -Это ускоряет взаимодействие и, вместе с операцией "провести пальцем, чтобы удалить", позволяет пользователю сосредоточиться на -важных для него уведомлениях.</p> - - - <img src="{@docRoot}images/android-5.0/notifications/action_combo.png" alt="" width="700px" /> - - - -<p style="clear:both">При определении количества действий в уведомлении следует проявлять -благоразумие. Чем больше -действий предоставлено пользователю, тем выше когнитивная сложность приложения. Ограничьтесь -минимальным количеством -действий, предоставив пользователю наиболее важные и -значимые.</p> - -<p>В уведомлениях отдавайте предпочтение действиям</p> - -<ul> - <li> важным, выполняемым наиболее часто и типичным для отображаемого -содержимого; - <li> позволяющим пользователю быстрее решить задачу. -</ul> - -<p>Избегайте действий</p> - -<ul> - <li> неоднозначных; - <li> совпадающих с действиями, выполняемыми для данного уведомления по умолчанию (например, "Прочитать" или -"Открыть"). -</ul> - - - -<p>Следует предоставлять не более трех действий, указав для каждого -значок и название. - Добавление действий в базовую компоновку делает уведомление расширяемым, -даже если - оно не имеет расширенной компоновки. Поскольку действия отображаются только у -расширенных - уведомлений, необходимо, чтобы любое действие, -которое пользователь может выполнить из - уведомления, было доступно и в соответствующем -приложении.</p> - -<h2 style="clear:left">Уведомления heads-up</h2> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/hun-example.png" alt="" width="311px" /> - <p class="img-caption"> - Пример уведомления heads-up (входящий телефонный звонок, высокий приоритет), -появляющегося поверх - приложения с эффектом присутствия - </p> -</div> - -<p>Когда поступает уведомление с высоким приоритетом (см. изображение справа), оно в течение короткого времени -отображается -в расширенной компоновке, позволяя выполнить допустимые действия.</p> -<p> Затем уведомление принимает обычный -вид. Если для уведомления установлен высокий, максимальный или полноэкранный <a href="#correctly_set_and_manage_notification_priority">приоритет</a> -, оно становится уведомлением heads-up.</p> - -<p><b>Хорошими примерами событий для уведомлений heads-up являются</b></p> - -<ul> - <li> входящий телефонный звонок, во время использования устройства;</li> - <li> сигнал будильника во время использования устройства;</li> - <li> новое SMS-сообщение;</li> - <li> низкий уровень заряда аккумулятора.</li> -</ul> - -<h2 style="clear:both" id="guidelines">Основные рекомендации</h2> - - -<h3 id="MakeItPersonal">Персонализируете уведомление</h3> - -<p>Уведомление о событии, инициированном другим пользователем (например, сообщение или -обновление статуса), должно содержать изображение пользователя, добавленное с помощью -{@link android.app.Notification.Builder#setLargeIcon setLargeIcon()}. Кроме того, в метаданные уведомления необходимо включить информацию о -пользователе (см. {@link android.app.Notification#EXTRA_PEOPLE}).</p> - -<p>Главный значок уведомления будет по-прежнему отображаться, чтобы пользователь мог связать -его со значком -на строке состояния.</p> - - -<img src="{@docRoot}images/android-5.0/notifications/Triggered.png" alt="" width="311px" /> -<p style="margin-top:10px" class="img-caption"> - Уведомление, идентифицирующее пользователя-инициатора, и отображающее отправленное содержимое. -</p> - - -<h3 id="navigate_to_the_right_place">Выполняйте переход в нужное место</h3> - -<p>Когда пользователь касается тела уведомления (за пределами кнопок -с действиями), должен осуществляться переход в то место приложения, -где пользователь сможет просмотреть информацию, о которой извещает уведомление, и действовать в соответствии -с нею. В большинстве случаев там будет находиться подробное представление одного элемента данных, например, сообщения, -но возможно и -сокращенное представление, если накопилось несколько уведомлений. Если приложение переводит -пользователя на какой-либо уровень, отличный от верхнего, реализуйте навигацию в стеке переходов назад в приложении, чтобы -пользователь мог нажать системную кнопку "Назад" и вернуться на верхний уровень. Дополнительную информацию можно найти в разделе -<em>Навигация внутрь приложения с помощью виджетов и уведомлений главного экрана</em> в шаблоне проектирования -<a href="{@docRoot}design/patterns/navigation.html#into-your-app">Навигация</a>.</p> - -<h3 id="correctly_set_and_manage_notification_priority">Правильно выполняйте расстановку приоритетов уведомлений и -управление ими -</h3> - -<p>Android поддерживает флаг приоритета для уведомлений. Это флаг позволяет -влиять на позицию уведомления среди других уведомлений и -гарантировать, -что пользователь в первую очередь увидит самые важные уведомления. При отправке уведомления можно выбрать один -из -следующих уровней приоритета:</p> -<table> - <tr> - <td class="tab0"> -<p><strong>Приоритет</strong></p> -</td> - <td class="tab0"> -<p><strong>Использование</strong></p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MAX</code></p> -</td> - <td class="tab1"> -<p>Применяйте для наиболее важных и неотложных уведомлений, извещающих пользователя -о ситуации, -критичной по времени или такой, на которую необходимо отреагировать, чтобы продолжить -выполнение задачи.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>HIGH</code></p> -</td> - <td class="tab1"> -<p>Применяйте, в основном, для передачи важной информации, например, о сообщениях или событиях -в чате с содержимым, представляющим особый интерес для пользователя. -Уведомления с высоким приоритетом отображаются как уведомления heads-up.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>DEFAULT</code></p> -</td> - <td class="tab1"> -<p>Применяйте для всех уведомлений, не входящих ни в одну из описанных здесь категорий.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>LOW</code></p> -</td> - <td class="tab1"> -<p>Применяйте для уведомлений, которые должны быть переданы пользователю, но -не являются неотложными. Низкоприоритетные уведомления обычно появляются в конце списка, -что позволяет использовать их -для передачи информации, представляющей всеобщий интерес и не имеющей конкретной направленности. Например, если пользователь подписался -на новости, - эта информация не должна иметь преимущество перед неотложными или адресными -сообщениями.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MIN</code></p> -</td> - <td class="tab1"> -<p>Применяйте для уведомлений, с контекстной или фоновой информацией, такой как прогноз погоды, или с информацией, -связанной с местоположением пользователя. -Уведомления с минимальным приоритетом не отображаются в строке состояния. Пользователь -обнаруживает их при раскрытии панели уведомления.</p> -</td> - </tr> -</table> - - -<h4 id="how_to_choose_an_appropriate_priority"><strong>Как выбрать -подходящий -приоритет</strong></h4> - -<p>При выдаче уведомлений с приоритетами <code>DEFAULT</code>, <code>HIGH</code> и <code>MAX</code> существует риск, что деятельность -пользователя будет прервана -в самом разгаре. Чтобы не раздражать пользователей вашего приложения, применяйте приоритеты этих уровней для -уведомлений,</p> - -<ul> - <li> имеющих отношение к другим пользователям;</li> - <li> быстро теряющих актуальность;</li> - <li> способных немедленно повлиять на поведение пользователя в реальном мире.</li> -</ul> - -<p>Уведомления с приоритетом <code>LOW</code> и <code>MIN</code> могут представлять определенную ценность -для пользователя. Значительное количество, если не большинство, уведомлений не требует немедленной -реакции пользователя, но, тем не менее, содержит информацию, которую пользователь сочтет -ценной, когда решит -просмотреть поступившие уведомления. Приоритеты уровней <code>LOW</code> и <code>MIN</code> - следует присваивать уведомлениям,</p> - -<ul> - <li> не имеющим прямого отношения к другим пользователям;</li> - <li> долго не теряющим актуальность;</li> - <li> содержащим информацию, способную заинтересовать пользователя, если он решит -просмотреть их в свободное время.</li> -</ul> - - - <img src="{@docRoot}images/android-5.0/notifications/notifications_pattern_priority.png" alt="" width="700" /> - - -<h3 style="clear:both" id="set_a_notification_category">Определите категорию -уведомления</h3> - -<p>Если уведомление попадает в одну из заранее определенных категорий (см. -ниже), укажите его -категорию. Процессы системного пользовательского интерфейса, например, панель уведомления (или любой -другой процесс-слушатель -уведомлений) могут воспользоваться этой информацией при классификации и фильтрации уведомлений.</p> -<table> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_CALL">CATEGORY_CALL</a></code></p> -</td> - <td> -<p>Входящий звонок (голосовой или по видеосвязи) или алогичный запрос синхронной -связи</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_MESSAGE">CATEGORY_MESSAGE</a></code></p> -</td> - <td> -<p>Входящее личное сообщение (SMS-сообщение, мгновенное сообщение и т. д.)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EMAIL">CATEGORY_EMAIL</a></code></p> -</td> - <td> -<p>Асинхронное массовое сообщение (по электронной почте)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EVENT">CATEGORY_EVENT</a></code></p> -</td> - <td> -<p>Событие в календаре</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROMO">CATEGORY_PROMO</a></code></p> -</td> - <td> -<p>Промоакция или реклама</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ALARM">CATEGORY_ALARM</a></code></p> -</td> - <td> -<p>Сигнал будильника или таймера</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROGRESS">CATEGORY_PROGRESS</a></code></p> -</td> - <td> -<p>Информация о ходе выполнения длительной фоновой операции</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SOCIAL">CATEGORY_SOCIAL</a></code></p> -</td> - <td> -<p>Новости, поступившие из социальной сети или касающиеся совместного использования ресурсов</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ERROR">CATEGORY_ERROR</a></code></p> -</td> - <td> -<p>Ошибка в фоновой операции или статусе аутентификации</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_TRANSPORT">CATEGORY_TRANSPORT</a></code></p> -</td> - <td> -<p>Управление передачей медиаданных для воспроизведения</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SYSTEM">CATEGORY_SYSTEM</a></code></p> -</td> - <td> -<p>Обновление статуса системы или устройства. Зарезервировано для использования системой.</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SERVICE">CATEGORY_SERVICE</a></code></p> -</td> - <td> -<p>Индикация работающей фоновой службы</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_RECOMMENDATION">CATEGORY_RECOMMENDATION</a></code></p> -</td> - <td> -<p>Конкретная и привязанная ко времени рекомендация относительно одного объекта. Например, приложение -новостей может -порекомендовать пользователю, какую новость читать следующей.</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_STATUS">CATEGORY_STATUS</a></code></p> -</td> - <td> -<p>Текущая информация о статусе устройства или контекста</p> -</td> - </tr> -</table> - -<h3 id="summarize_your_notifications">Суммируйте уведомления</h3> - -<p>Если при наличии ожидающего уведомления определенного типа приложение пытается отправить новое -уведомление того же типа, объедините их в одно сводное уведомление от этого приложения. Не -создавайте новый объект.</p> - -<p>Сводное уведомление формирует сводное описание и дает пользователю возможность -понять, сколько -имеется ожидающих уведомлений того или иного типа.</p> - -<div class="col-6"> - -<p><strong>Неправильно</strong></p> - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Dont.png" alt="" width="311px" /> -</div> - -<div> -<p><strong>Правильно</strong></p> - - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Do.png" alt="" width="311px" /> -</div> - -<p style="clear:left; padding-top:30px; padding-bottom:20px">Разработчик может сообщить -подробности об отдельных уведомлениях, образующих - сводное, используя расширенную компоновку для резюме. Такой подход позволит пользователям -лучше разобраться, какие -уведомления ожидают прочтения, и достаточно ли они интересны, чтобы ознакомиться с ними -более подробно в - соответствующем приложении.</p> -<div class="col-6"> - <img src="{@docRoot}images/android-5.0/notifications/Stack.png" style="margin-bottom:20px" alt="" width="311px" /> - <p class="img-caption"> - Расширенное и сжатое сводное уведомление (с использованием <code>InboxStyle</code>) - </p> -</div> - -<h3 style="clear:both" id="make_notifications_optional">Сделайте уведомления -необязательными</h3> - -<p>В распоряжении пользователей всегда должен быть метод управления уведомлениями. Предоставьте пользователю возможность -отключать уведомления, поступающие от вашего приложения, -или изменять способы оповещения, такие как звуковой сигнал и -вибрация. - С этой целью следует предусмотреть пункт настройки уведомлений в настройках приложения.</p> - -<h3 id="use_distinct_icons">Используйте отчетливые значки</h3> -<p>Беглого взгляда на область уведомлений должно быть достаточно, чтобы распознать -типы -ожидающих уведомлений.</p> - -<div class="figure"> - <img src="{@docRoot}images/android-5.0/notifications/ProductIcons.png" alt="" width="420" /> -</div> - - <div><p><strong>Правильно</strong></p> - <p>Рассмотрите уже существующие значки уведомлений от приложений Android и создайте -собственные, - достаточно уникальные.</p> - - <p><strong>Правильно</strong></p> - <p>Придерживайтесь подходящего <a href="/design/style/iconography.html#notification">стиля значков уведомления</a> - для мелких значков, и - <a href="/design/style/iconography.html#action-bar">стиля строки -действий</a> Material Light для значков - действий.</p> -<p ><strong>Правильно</strong></p> -<p >Стремитесь к визуальной простоте значков, избегайте излишних трудноразличимых -деталей.</p> - - <div><p><strong>Неправильно</strong></p> - <p>Применяйте к мелким значкам и значкам действий дополнительные альфа-эффекты -(постепенное появление/исчезание). - К их краям может быть применено сглаживание, но, поскольку в Android эти значки -служат масками (то есть, - используется только альфа-канал), изображение, как правило, должно отображаться полностью -непрозрачным.</p> - -</div> -<p style="clear:both"><strong>Неправильно</strong></p> - -<p>Чтобы ваше приложение отличалось от других, используйте цвет. Значки уведомлений должны -представлять собой изображение белого цвета на прозрачном фоне.</p> - - -<h3 id="pulse_the_notification_led_appropriately">Правильно используйте индикатор -уведомлений</h3> - -<p>На многих устройствах Android имеется светодиодный индикатор уведомлений, -информирующий пользователя о -событиях, когда экран выключен. Уведомления с приоритетом <code>MAX</code>, -<code>HIGH</code> или <code>DEFAULT</code> должны -вызывать свечение индикатора, а уведомления с низким приоритетом (<code>LOW</code> и -<code>MIN</code>) не должны.</p> - -<p>Возможности пользователя управлять уведомлениями должны распространяться на светодиодный индикатор. Когда разработчик использует -DEFAULT_LIGHTS, -индикатор светится белым цветом. Ваши уведомления не должны вызывать свечение другим -цветом, если -пользователь не указал этого явным образом.</p> - -<h2 id="building_notifications_that_users_care_about">Создание уведомлений, - важных для пользователя</h2> - -<p>Чтобы пользователям понравилось ваше приложение, необходимо тщательно -продумать его уведомления. -Уведомления — это голос приложения. Они определяют его -индивидуальность. Ненужные или -несущественные уведомления раздражают пользователя и заставляют его возмущаться тем, как много -внимания требует от него -приложение. Поэтому необходимо применять уведомления взвешенно.</p> - -<h3 id="when_to_display_a_notification">Ситуации, в которых следует показывать уведомления</h3> - -<p>Чтобы создать приложение, от работы с которым пользователи получат удовольствие, необходимо -осознать, что внимание пользователя - является ресурсом, требующим бережного обращения. Система уведомлений -Android была разработана -так, чтобы как можно меньше отвлекать пользователя. -Однако -вы должны отдавать себе отчет в том, что уведомления прерывают -деятельность пользователя. -Планируя уведомления, спрашивайте себя, достаточно ли они важны, чтобы -послужить основанием для такого прерывания. В случае сомнений предоставьте пользователю возможность запросить -в настройках приложения получение уведомления или измените -приоритет уведомления на <code>LOW</code> или <code>MIN</code>, чтобы -не отвлекать пользователя от -текущих занятий.</p> - - <img src="{@docRoot}images/android-5.0/notifications/TimeSensitive.png" alt="" width="311px" /> - <p style="margin-top:10px" class="img-caption"> - Примеры уведомлений, быстро теряющих актуальность - </p> - -<p>Хотя правильно работающие приложения ведут себя неназойливо, бывают ситуации, -заслуживающие того, чтобы приложение по своей инициативе прервало деятельность пользователя уведомлением.</p> - -<p>Отправляйте уведомления только в случае <strong>событий, требующих неотложной реакции</strong>, особенно - если эти синхронные события <strong>имеют прямое отношение к другим пользователям</strong>. Например, -чат - представляет собой форму синхронного общения в реальном времени, — другой пользователь -с нетерпением ожидает вашего ответа. События в календаре являются еще одним хорошим примером ситуации, в которой следует выдать -уведомление и завладеть - вниманием пользователя, потому что в приближающееся календарное событие часто -вовлечены другие люди.</p> - -<h3 style="clear:both" id="when_not_to_display_a_notification">Ситуации, -в которых не следует показывать уведомления</h3> - -<div class="figure" style="margin-top:60px"> - <img src="{@docRoot}images/android-5.0/notifications/AntiSample1.png" alt="" width="311px" /> -</div> - -<p>В большинстве остальных случаев уведомления неуместны.</p> - -<ul> - <li> Не следует извещать пользователя о событиях, не имеющих отношения -к нему конкретно, или - не теряющих актуальность со временем. Например, асинхронные -и безадресные новости, - циркулирующие в социальных сетях, как правило, не требуют немедленного -привлечения внимания. Пользователям, - действительно интересующимся таким новостями, предоставьте возможность запросить соответствующие уведомления.</li> - <li> Не генерируйте уведомление, если релевантная свежая информация уже находится -на экране. Вместо этого - воспользуйтесь интерфейсом самого приложения, чтобы донести до пользователя новую информацию -непосредственно в контексте. - Например, приложение-чат не должно генерировать системные уведомления, -пока пользователь активно общается с собеседником.</li> - <li> Не отвлекайте пользователя ради низкоуровневых технических действий, такие как сохранение -или синхронизация информации или обновление приложения, если приложение или система способны выполнить задачу -без вмешательства пользователя.</li> - <li> Не отвлекайте пользователя, чтобы проинформировать его об ошибке, если -приложение может восстановиться после нее самостоятельно, не требуя от пользователя -никаких действий.</li> - <li> Не создавайте уведомления, не имеющие осмысленного содержимого и -всего лишь рекламирующие ваше -приложение. Уведомление должно нести полезную, актуальную и новую информацию. Не следует -использовать его - исключительно для презентации приложения.</li> - <li> Не создавайте избыточные уведомления только для того, чтобы продемонстрировать свой бренд -пользователям. - Такие уведомления раздражают и отталкивают аудиторию. Лучший -способ сообщать - новую информацию небольшими порциями и поддерживать связь пользователей -с вашим - приложением заключается в том, чтобы разработать виджет, который они смогут поместить на - главный экран.</li> -</ul> - -<h2 style="clear:left" id="interacting_with_notifications">Взаимодействие с -уведомлениями</h2> - -<p>Уведомления обозначаются значками в строке состояния. Чтобы получить к ним доступ, -следует открыть -панель уведомлений.</p> - -<p>Если коснуться уведомления, откроется соответствующее приложение с подробным содержимым, -связанным с эти уведомлением. -Если провести пальцем по уведомлению влево или вправо, оно будет удалено из панели.</p> - -<h3 id="ongoing_notifications">Постоянные уведомления</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/MusicPlayback.png" alt="" width="311px" /> - <p class="img-caption"> - Постоянные уведомления при воспроизведении музыки - </p> -</div> -<p>Постоянные уведомления информируют пользователя о текущих фоновых -процессах. -Например, плееры сообщают через систему уведомлений информацию о дорожке, -воспроизводимой в данный момент, и -это продолжается, пока пользователь не остановит воспроизведение. Кроме того, постоянные уведомления могут -информировать пользователя -о ходе выполнения длительных задач, таких как загрузка файла или кодирование видеоданных. Пользователь не может вручную -удалить постоянное уведомление из панели уведомлений.</p> - -<h3 id="ongoing_notifications">Воспроизведение медиаданных</h3> -<p>В Android 5.0 на экране блокировки не отображаются элементы управления воспроизведением от устаревшего -класса {@link android.media.RemoteControlClient}. Однако на нем <em>отображаются</em> уведомления, так что теперь каждое -уведомление приложения о воспроизведении является для пользователей основным -способом управления воспроизведением в заблокированном состоянии. В результате у приложения появляется больше возможностей -управлять тем, какие -кнопки отображать, и каким образом. При этом с точки зрения пользователя система ведет себя непротиворечиво, -независимо от того, заблокирован ли экран.</p> - -<h3 style="clear:both" -id="dialogs_and_toasts_are_for_feedback_not_notification">Диалоговые окна -и всплывающие уведомления</h3> - -<p>Приложение, не отображаемое на экране, не должно генерировать диалоговое окно или всплывающее -уведомление. Диалоговое окно или всплывающее уведомление - должно появляться исключительно в качестве немедленной реакции на действия пользователя -в приложении. -Более подробные рекомендации по использованию диалоговых окон и всплывающих уведомлений см. в разделе -<a href="/design/patterns/confirming-acknowledging.html">Подтверждение и уведомление</a>.</p> - -<h3>Упорядочение уведомлений по степени важности</h3> - -<p>По своей сути уведомления — это новости, и поэтому они принципиально отображаются в -обратном хронологическом порядке. -При этом обязательно принимается во внимание -<a href="#correctly_set_and_manage_notification_priority">приоритет</a>, установленный приложением.</p> - -<p>Уведомления являются важной составляющей экрана блокировки и отображаются на видном месте -каждый -раз, когда включается дисплей устройства. На экране блокировки мало свободного места, поэтому -исключительно важно -выявлять неотложные или наиболее релевантные уведомления. По этой -причине Android применяет -сложный алгоритм сортировки уведомлений, в котором учитываются</p> - -<ul> - <li> временная метка и приоритет, установленный приложением;</li> - <li> тот факт, что уведомление только что оповестило пользователя звуковым сигналом -или вибрацией (иными словами, - если телефон издает звуки, и пользователь хочет узнать, в чем -дело, то на экране блокировки - должен находиться ответ, понятный с первого взгляда);</li> - <li> пользователи, связанные с уведомлением при помощи {@link android.app.Notification#EXTRA_PEOPLE}, - и, в частности, присутствие их в списке помеченных контактов.</li> -</ul> - -<p>Чтобы воспользоваться преимуществами этой сортировки наилучшим образом, думайте в первую очередь о создании -удобных условий для -пользователя, и не нацеливайтесь на конкретное место в рейтинге.</p> - - <img src="{@docRoot}images/android-5.0/notifications/AntiSample3.png" alt="" width="700px" /> - - <p class="img-caption" style="margin-top:10px">Уведомления от Gmail имеют -приоритет DEFAULT, поэтому они - обычно оказываются ниже уведомлений от приложений мгновенного обмена сообщениями, таких как Hangouts, но -поднимаются в списке - на некоторое время, когда поступают новые сообщения. - </p> - - -<h3>Уведомления на экране блокировки</h3> - -<p>Поскольку уведомления видны на экране блокировки, защита конфиденциальной информации пользователей приобретает -особо -важное значение. Уведомления нередко содержат частную информацию, и они -не должны быть доступны -каждому, кто взял в руки устройство и включил дисплей.</p> - -<ul> - <li> У устройств, экран блокировки которых защищен (при помощи PIN-кода, графического ключа или пароля), интерфейс имеет - общедоступную и закрытую части. Элементы общедоступного интерфейса отображаются на защищенном экране блокировки и - следовательно, видны всем. Закрытый интерфейс находится "позади" экрана блокировки и - доступен только пользователю, выполнившему вход в устройство.</li> -</ul> - -<h3>Возможности пользователя контролировать информацию, отображаемую на экране блокировки</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/LockScreen@2x.png" srcset="{@docRoot}images/android-5.0/notifications/LockScreen.png 1x" alt="" width="311px" /> - <p class="img-caption"> - Уведомления на экране блокировки с содержимым, отображаемым после того, как пользователь разблокирует устройство. - </p> -</div> - -<p>При настройке защиты экрана блокировки пользователь может предпочесть, - чтобы конфиденциальные данные не отображались на защищенном экране блокировки. В этом случае системный пользовательский интерфейс -учитывает <em>уровень видимости</em> уведомления, чтобы выяснить, какую информацию -можно отображать без риска.</p> -<p> Чтобы установить уровень видимости, вызовите -<code><a -href="/reference/android/app/Notification.Builder.html#setVisibility(int)">Notification.Builder.setVisibility()</a></code> -и укажите одно из следующих значений:</p> - -<ul> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PUBLIC">VISIBILITY_PUBLIC</a></code>. -Содержимое уведомления отображается полностью. - Это значение принимается системой по умолчанию, если уровень видимости не указан.</li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PRIVATE">VISIBILITY_PRIVATE</a></code>. -На экране блокировки отображается основная информация о наличии уведомления, включая его -значок и название приложения, отправившего его. Прочие данные уведомления скрыты. -Здесь уместно дать разработчику пару рекомендаций. - <ul> - <li> Если вы хотите реализовать отдельную общедоступную версию уведомления, -которую система будет отображать на экране блокировки, создайте замещающий -объект Notification в поле<code><a -href="/reference/android/app/Notification.html#publicVersion">Notification.publicVersion</a></code>. - - <li> Этот параметр предоставляет приложению возможность создавать "цензурированную" версию -содержимого, достаточно информативную, но скрывающую личную информацию. Рассмотрим в качестве примера приложение для отправки -SMS-сообщений. Его уведомления содержат текст SMS-сообщения и имя и контактный значок отправителя. -Такое уведомление должно иметь атрибут <code>VISIBILITY_PRIVATE</code>, но его версия <code>publicVersion</code> может -содержать полезную информацию, например, "3 новых сообщения", без уточняющих -подробностей. - </ul> - </li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_SECRET">Notification.VISIBILITY_SECRET</a></code>. Отображается минимум информации, -даже без значка уведомления.</li> -</ul> -<h2 style="clear:both" id="notifications_on_android_wear">Уведомления на -Android Wear</h2> - -<p>По умолчанию уведомления и их <em>действия</em> передаются на носимые устройства. -Разработчики могут управлять тем, какие уведомления следует передавать с -телефона на часы, -и наоборот. У разработчиков также есть возможность управлять передачей действий. Если -приложение включает в себя -действия, которые невозможно выполнить одним касанием, нужно либо скрывать их -в уведомлениях, отображаемых на носимом -устройстве, либо обеспечить их привязку к приложению под управлением Android Wear, позволив пользователю -совершать действие -на часах.</p> - -<h4>Передача уведомлений и действий на другое устройство</h4> - -<p>Подключенное устройство, например, телефон, может передавать уведомления на носимое устройство, -чтобы они отображались и на нем. Аналогичным образом можно передавать действия, чтобы пользователь мог реагировать -на уведомления непосредственно на носимом устройстве.</p> - -<p><strong>Передавайте</strong></p> - -<ul> - <li> новые мгновенные сообщения;</li> - <li> действия, выполняемые одним касанием, например, "+1", "Лайк", "Сердечко".</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/WearBasic.png" width="156px" height="156px" alt="" /> - -<p><strong>Не передавайте</strong></p> - -<ul> - <li> уведомления о новых подкастах;</li> - <li> действия, соответствующие функциям, недоступным на часах.</li> -</ul> - - - -<p><h4>Уникальные действия, определяемые для носимых устройств</h4></p> - -<p>Некоторые действия можно выполнить только на носимых устройствах, например:</p> - -<ul> - <li> выбор из списка шаблонных ответов, например, "Скоро вернусь"</li> - <li> действие "Открыть на телефоне";</li> - <li> действия "Прокомментировать" или "Ответить", открывающие окно речевого ввода;</li> - <li> действия, запускающие приложения, специфичные для Android Wear.</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/ReplyAction.png" width="156px" height="156px" alt="" /> diff --git a/docs/html-intl/intl/zh-cn/design/patterns/notifications.jd b/docs/html-intl/intl/zh-cn/design/patterns/notifications.jd deleted file mode 100644 index 57e02e44942c..000000000000 --- a/docs/html-intl/intl/zh-cn/design/patterns/notifications.jd +++ /dev/null @@ -1,872 +0,0 @@ -page.title=通知 -page.tags="notifications","design","L" -@jd:body - - <a class="notice-developers" href="{@docRoot}training/notify-user/index.html"> - <div> - <h3>开发者文档</h3> - <p>通知用户</p> - </div> -</a> - -<a class="notice-designers" href="notifications_k.html"> - <div> - <h3>Android 4.4 及更低版本中的通知</h3> - </div> -</a> - -<!-- video box --> -<a class="notice-developers-video" href="https://www.youtube.com/watch?v=Uiq2kZ2JHVY"> -<div> - <h3>视频</h3> - <p>DevBytes:Android L 开发者预览当中的通知</p> -</div> -</a> - -<style> - .col-5, .col-6, .col-7 { - margin-left:0px; - } -</style> - -<p>通知系统可让用户随时了解应用中的相关和即时事件,例如来自好友的新聊天信息或日历事件。可将通知视作新闻频道,在重要的事件发生时提醒用户注意,或者当作日志,在用户未注意时记录事件—可在用户的所有 Android 设备上按需同步。 - - - - - -</p> - -<h4 id="New"><strong>Android 5.0 新增内容</strong></h4> - -<p>在 Android 5.0 中,通知在结构、外观和功能方面获得了重要的更新: -</p> - -<ul> - <li>通知在外观上发生了更改,与新的材料设计主题保持一致。 -</li> - <li> 通知现在可以在设备锁定屏幕上使用,而敏感信息仍然可以隐藏于背后。 - -</li> - <li>设备在使用时收到的高优先级通知现在采用名为浮动通知的新格式。 -</li> - <li>云同步通知:在一台 Android 设备上清除通知,则在其他设备上也会将其清除。 - -</li> -</ul> - -<p class="note"><strong>注:</strong>该版本 Android 的通知设计与之前的版本大不相同。 - -有关之前版本通知设计的信息,请参阅<a href="./notifications_k.html"> Android 4.4 及更低版本中的通知</a>。 -</p> - -<h2 id="Anatomy">通知详解</h2> - -<p>本部分介绍通知的基本组成部分,及其在不同类型设备上显示的方式。 -</p> - -<h3 id="BaseLayout">基本布局</h3> - -<p>所有通知至少要包括一个基本布局,包括:</p> - -<ul> - <li> 通知的<strong>图标</strong>。图标以符号形式表示来源应用。如果应用生成多个类型的通知,它也可用于指明通知类型。 - - -</li> - <li> 通知<strong>标题</strong>以及其他 -<strong>文本</strong>。</li> - <li> <strong>时间戳</strong>。</li> -</ul> - -<p>利用 {@link android.app.Notification.Builder Notification.Builder}为之前版本平台创建的通知,其外观和行为方式与在 Android -5.0 中完全相同,唯一的变动在于系统为您处理通知的方式存在细微的样式变动。 - -如需了解之前 Android 版本通知设计的详细信息,请参阅<a href="./notifications_k.html"> Android 4.4 及更低版本中的通知</a>。 - -</p></p> - - - <img style="margin:20px 0 0 0" src="{@docRoot}images/android-5.0/notifications/basic_combo.png" alt="" width="700px" /> - - -<div style="clear:both;margin-top:20px"> - <p class="img-caption"> - 手持设备通知(左)和穿戴设备(右)上同一通知的基本布局,带有用户照片和通知图标 - - </p> - </div> - -<h3 id="ExpandedLayouts">展开布局</h3> - - -<p>您可以选择让应用的通知提供多少信息详情。 -它们可显示消息的前几行,也可以显示更大的预览图像。 -额外的信息可以为用户提供更多上下文,并且,在某些情况下,可能允许用户完整阅读消息。 - - -用户可进行两指缩放或执行单指滑移,在紧凑和展开布局之间切换。 - - - 对于单一事件通知,Android 提供了三种展开布局模板(文本、收件箱和图像),供您在应用中使用。 - -下图展示单一事件通知在手持设备(左)和穿戴式设备(右)上的外观。 - -</p> - -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/expandedtext_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/stack_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/ExpandedImage.png" - alt="" width="311px" height;="450px" /> - -<h3 id="actions" style="clear:both; margin-top:40px">操作</h3> - -<p>Android 支持在通知底部显示可选的操作。通过操作,用户可在通知栏中处理最常见的任务,而无需打开来源应用。这样可加快交互的速度,而通过结合使用滑动清除通知的功能,有助于用户专注于对自身重要的通知。 - - - - - -</p> - - - <img src="{@docRoot}images/android-5.0/notifications/action_combo.png" alt="" width="700px" /> - - - -<p style="clear:both">请慎重考虑要在通知中包含多少操作。 -您加入的操作越多,用户就越无所适从。 -请通过只包含最重要且有意义的操作,尽量减少通知中的操作数量。 - - -</p> - -<p>适合在通知中使用的操作具有如下特点:</p> - -<ul> - <li> 对正在显示的内容类型必要、常用且常见 - - <li> 让用户可以迅速完成任务 -</ul> - -<p>避免以下类型的操作:</p> - -<ul> - <li> 含义模糊 - <li> 跟通知的默认操作一样(例如“阅读”或“打开”) - -</ul> - - - -<p>您最多可以指定三个操作,每个操作由操作图标和名称组成。 - - 通过为简单的基本布局添加操作,可以展开该通知,即使该通知没有展开布局,此方法仍然有效。 - -由于操作仅对展开的通知显示(否则会隐藏),因此要确保用户从通知调用的任何操作都可在相关联的应用中使用。 - - - - -</p> - -<h2 style="clear:left">浮动通知</h2> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/hun-example.png" alt="" width="311px" /> - <p class="img-caption"> - 出现在沉浸式应用顶部的浮动通知(手机来电,高优先级)示例 - - - </p> -</div> - -<p>收到高优先级通知时(见右侧),它会向用户短时间显示一个包含可选操作的展开布局。 - -</p> -<p> 之后,通知会缩回通知栏。 -如果通知的<a href="#correctly_set_and_manage_notification_priority">优先级</a>标志为高、最大或全屏,则会得到浮动通知。 -</p> - -<p><b>浮动通知的范例</b></p> - -<ul> - <li> 使用设备时来电</li> - <li> 使用设备时闹铃</li> - <li> 新的短信</li> - <li> 电池电量过低</li> -</ul> - -<h2 style="clear:both" id="guidelines">指导原则</h2> - - -<h3 id="MakeItPersonal">个人化</h3> - -<p>对于他人发送的项目通知(例如消息或状态更新),请使用 -{@link android.app.Notification.Builder#setLargeIcon setLargeIcon()} 包含此人的头像。 -另外将有关此人的信息附加到通知的元数据(参阅 {@link android.app.Notification#EXTRA_PEOPLE})。 -</p> - -<p>您通知的主图标仍然会显示,因此,该用户可将其与状态栏中显示的图标相关联。 - -</p> - - -<img src="{@docRoot}images/android-5.0/notifications/Triggered.png" alt="" width="311px" /> -<p style="margin-top:10px" class="img-caption"> - 显示触发通知的用户以及该用户所发送信息的通知。 -</p> - - -<h3 id="navigate_to_the_right_place">导航至正确位置</h3> - -<p>在用户触摸通知的正文时(在操作按钮的外面),打开应用并定位至正确的位置,以便用户可查看通知中引用的数据并据此操作。 - - -在大多数情况下,该位置是某个数据项目(例如消息)的详情视图,但如果是存档通知,那么也可能是摘要视图。 - -如果您的应用将用户带到应用顶层以下的任何位置,可将导航插入应用的返回栈,这样用户就可以通过按下系统返回按钮返回至顶层。 - -如需了解详细信息,请参阅<a href="{@docRoot}design/patterns/navigation.html#into-your-app">导航</a>设计模式中的“通过主屏幕小工具和通知进入您的应用”<em></em>。 - -</p> - -<h3 id="correctly_set_and_manage_notification_priority">正确设置和管理通知优先级。 - -</h3> - -<p>Android 支持通知的优先级标志。该标志可以影响您的通知相对于其他通知出现的位置,并且可以帮助确保用户始终能在第一时间看到对他们最重要的通知。 - - -在发布通知时,您可以选择下列优先级之一: - -</p> -<table> - <tr> - <td class="tab0"> -<p><strong>优先级</strong></p> -</td> - <td class="tab0"> -<p><strong>用法</strong></p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MAX</code></p> -</td> - <td class="tab1"> -<p>用于重要和紧急的通知,告知用户属于时间关键型状况,或者必须予以解决方可继续执行某个特定任务。 - - -</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>HIGH</code></p> -</td> - <td class="tab1"> -<p>主要用于重要通信,例如包含用户特别感兴趣的内容的消息或聊天事件。高优先级通知会触发浮动通知显示。 - -</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>DEFAULT</code></p> -</td> - <td class="tab1"> -<p>用于不属于此处所述其他任何优先级的所有通知。</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>LOW</code></p> -</td> - <td class="tab1"> -<p>用于您希望告知用户但不是很紧急的通知。 -低优先级通知最好显示在列表的底部,这里正适合放置公共事项或无收件人姓名的社交更新之类的通知: - -用户要求接收相关通知,但是这些通知的优先级永远不会高于紧急或直接通信。 - - -</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MIN</code></p> -</td> - <td class="tab1"> -<p>用于上下文或背景信息,例如天气信息或上下文位置信息。最低优先级通知不会出现在状态栏中。 - -用户可在展开的通知栏上找到它们。 -</p> -</td> - </tr> -</table> - - -<h4 id="how_to_choose_an_appropriate_priority"><strong>如何选择合适的优先级</strong> - -</h4> - -<p><code>DEFAULT</code>、<code>HIGH</code> 和 <code>MAX</code> 是中断优先级别,在活动过程中有中断用户的风险。 - -为了避免打扰应用的用户,中断优先级仅保留用于以下通知 -:</p> - -<ul> - <li> 涉及另一个用户</li> - <li> 时间敏感</li> - <li> 可能会立即改变用户在现实世界中的行为</li> -</ul> - -<p>设置为 <code>LOW</code> 和 <code>MIN</code> 的通知可能仍然对用户很重要: -很多通知(如果不是绝大多数)不需要用户立即注意,也不需要振动,但仍然包含用户选择查看通知时将会觉得重要的信息。 - - -<code>LOW</code> 和 <code>MIN</code>优先级通知的条件包括: -</p> - -<ul> - <li> 不涉及其他用户</li> - <li> 不属于时间敏感型</li> - <li> 包含用户可能感兴趣但可选择在空闲时浏览的内容 -</li> -</ul> - - - <img src="{@docRoot}images/android-5.0/notifications/notifications_pattern_priority.png" alt="" width="700" /> - - -<h3 style="clear:both" id="set_a_notification_category">设置通知类别 -</h3> - -<p>如果通知属于以下预定义类别(参阅下文)之一,则为其分配相应的类别。 - -诸如通知栏(或其他任何通知侦听器)这样的系统 UI 项目,可使用该信息来进行评级和筛选决策。 - -</p> -<table> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_CALL">CATEGORY_CALL</a></code></p> -</td> - <td> -<p>来电(语音或视频)或相似的同步通信请求 -</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_MESSAGE">CATEGORY_MESSAGE</a></code></p> -</td> - <td> -<p>传入的直接消息(短信、即时消息等)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EMAIL">CATEGORY_EMAIL</a></code></p> -</td> - <td> -<p>异步群发消息(电子邮件)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EVENT">CATEGORY_EVENT</a></code></p> -</td> - <td> -<p>日历事件</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROMO">CATEGORY_PROMO</a></code></p> -</td> - <td> -<p>促销或广告</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ALARM">CATEGORY_ALARM</a></code></p> -</td> - <td> -<p>闹铃或定时器</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROGRESS">CATEGORY_PROGRESS</a></code></p> -</td> - <td> -<p>长时间运行的后台操作的进度</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SOCIAL">CATEGORY_SOCIAL</a></code></p> -</td> - <td> -<p>社交网络或共享更新</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ERROR">CATEGORY_ERROR</a></code></p> -</td> - <td> -<p>后台操作或身份验证状态中的错误</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_TRANSPORT">CATEGORY_TRANSPORT</a></code></p> -</td> - <td> -<p>媒体传输播放控制</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SYSTEM">CATEGORY_SYSTEM</a></code></p> -</td> - <td> -<p>系统或设备状态更新。保留给系统使用。</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SERVICE">CATEGORY_SERVICE</a></code></p> -</td> - <td> -<p>正在运行的后台服务的指示</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_RECOMMENDATION">CATEGORY_RECOMMENDATION</a></code></p> -</td> - <td> -<p>对于某个事件的特定、及时建议。例如,新闻应用可能会建议用户接下来可能想要阅读的新话题。 - -</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_STATUS">CATEGORY_STATUS</a></code></p> -</td> - <td> -<p>有关设备或上下文状态的持续信息</p> -</td> - </tr> -</table> - -<h3 id="summarize_your_notifications">通知摘要</h3> - -<p>如果特定类型的通知已经在您的应用尝试发送同类型的新通知时挂起,可将它们合并到单个应用摘要通知中,而不要新建对象。 - -</p> - -<p>摘要通知会生成摘要说明,让用户了解特定类型的通知有多少处于挂起状态。 - -</p> - -<div class="col-6"> - -<p><strong>禁忌用法</strong></p> - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Dont.png" alt="" width="311px" /> -</div> - -<div> -<p><strong>建议用法</strong></p> - - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Do.png" alt="" width="311px" /> -</div> - -<p style="clear:left; padding-top:30px; padding-bottom:20px">您可通过使用展开的摘要布局提供有关组成摘要的各个通知的更多详情。 - -此方法可让用户更好地了解哪些通知处于挂起状态,如果他们有足够的兴趣,还可在相关联的应用中阅读详情。 - - - -</p> -<div class="col-6"> - <img src="{@docRoot}images/android-5.0/notifications/Stack.png" style="margin-bottom:20px" alt="" width="311px" /> - <p class="img-caption"> - 展开和收起的摘要通知(使用 <code>InboxStyle</code>) - </p> -</div> - -<h3 style="clear:both" id="make_notifications_optional">将通知设置为可选 -</h3> - -<p>用户应始终能控制通知。允许用户通过将某个通知设置项目添加至您的应用设置,禁用应用的通知或更改其提醒属性,例如警报声和是否使用振动。 - - - -</p> - -<h3 id="use_distinct_icons">使用不同的图标</h3> -<p>通过扫一眼通知区域,用户可以了解哪些类型的通知当前处于挂起状态。 - -</p> - -<div class="figure"> - <img src="{@docRoot}images/android-5.0/notifications/ProductIcons.png" alt="" width="420" /> -</div> - - <div><p><strong>建议用法</strong></p> - <p>查看 Android 应用已经提供的通知图标并为您的应用创建外观明显不同的通知图标。 - -</p> - - <p><strong>建议用法</strong></p> - <p>对小图标使用正确的<a href="/design/style/iconography.html#notification">通知图标样式</a>,对操作图标使用相应的材料灯<a href="/design/style/iconography.html#action-bar">操作栏图标</a>。 - - - -</p> -<p ><strong>建议用法</strong></p> -<p >图标外观要简洁清晰,避免使用过于精细、难以辨认的图标。 -</p> - - <div><p><strong>禁忌用法</strong></p> - <p>对小图标和操作图标设置任何附加的阿尔法通道属性(变暗或变淡);这些图标会有抗锯齿边缘,但是由于 Android 使用这些图标作为蒙板(即仅使用阿尔法通道),因此通常应以完全不透明的方式绘制图像。 - - - - -</p> - -</div> -<p style="clear:both"><strong>禁忌用法</strong></p> - -<p>利用色彩将您的应用与其他应用区分开来。通知图标应该是纯白透明背景图像。 -</p> - - -<h3 id="pulse_the_notification_led_appropriately">对通知 LED 施加相应的脉冲 -</h3> - -<p>许多 Android 设备都配有通知 LED,用于让用户在屏幕关闭时了解事件。 - -优先级为 <code>MAX</code>、 -<code>HIGH</code> 或 <code>DEFAULT</code> 的通知应让 LED 发光,而优先级较低的通知(<code>LOW</code> 和 <code>MIN</code>)则不应让 LED 发光。 - -</p> - -<p>用户对通知的控制应延伸至 LED。当您使用 DEFAULT_LIGHTS 时,LED 将发出白光。 - -您的通知不应使用不同的颜色,除非用户明确对其进行了自定义。 - -</p> - -<h2 id="building_notifications_that_users_care_about">构建用户关注的通知 -</h2> - -<p>要创建用户喜爱的应用,精心设计通知很重要。通知是应用的代言人,还可增强应用的个性化特征。 - - -无用或者不重要的通知会给用户带来烦恼,或者由于过分分散用户的注意力而使其感到愤怒,因此请谨慎使用通知。 - - -</p> - -<h3 id="when_to_display_a_notification">何时显示通知</h3> - -<p>要创建人们乐于使用的应用,就需要认识到用户的注意力和关注点是一种必须予以保护的资源,这一点很重要。 - -尽管 Android 的通知系统在设计上希望最小化通知对用户注意力的影响,但是仍然要重视通知会中断用户任务流程这一事实。在您计划通知时,要问问自己,它们是否足够重要,是否适合让用户中断手上的任务。 - - - - - - -如果您不确定,可允许用户使用应用的通知设置来选择是否接收通知,或者将通知优先级标志调整为 <code>LOW</code> 或 <code>MIN</code>,从而避免在用户做其他事情时分散他们的注意力。 - - - -</p> - - <img src="{@docRoot}images/android-5.0/notifications/TimeSensitive.png" alt="" width="311px" /> - <p style="margin-top:10px" class="img-caption"> - 时间敏感通知的示例 - </p> - -<p>尽管行为良好的应用通常只在用户对其操作后才会发出通知,但在极少数情况下,应用通过无提示的通知形式打断用户也是值得的。 -</p> - -<p>将通知主要用于<strong>时间敏感的事件</strong>,尤其是这些同步事件<strong>涉及其他用户时</strong>。 -例如,传入的聊天属于实时同步通信形式: - -另一个用户在主动等待您的回应。 -日历事件是使用通知并引起用户注意的另一个好例子,因为事件已经迫近,并且日历事件通常涉及其他人员。 - - -</p> - -<h3 style="clear:both" id="when_not_to_display_a_notification">何时不显示通知 -</h3> - -<div class="figure" style="margin-top:60px"> - <img src="{@docRoot}images/android-5.0/notifications/AntiSample1.png" alt="" width="311px" /> -</div> - -<p>在其他很多情况下都不适合显示通知:</p> - -<ul> - <li> 不要将并非特定于用户的信息或并非确实时间敏感的信息告知用户。 - -例如,流经社交网络的异步和未经订阅的更新,通常不适合引发实时中断。 - - -对于确实关注它们的用户,可让他们选择接收通知。 -</li> - <li> 如果相关的新信息当前显示在屏幕上,则不要创建通知。 -不过可以使用应用本身的 UI 在上下文中将新信息直接告知用户。 - - - 例如,聊天应用不应在用户主动和另一名用户聊天时创建系统通知。 -</li> - <li> 对于技术要求不高的操作(例如保存或同步信息或更新应用),如果应用或系统无需用户参与就可解决问题,请不要中断用户。 - -</li> - <li> 如果可以让应用自行恢复错误,而不必让用户采取任何操作,则不要中断用户来告知他们发生此错误。 - -</li> - <li> 请不要创建没有实际通知内容和仅仅是为您的应用做宣传的通知。通知应当提供有用、及时、最新的信息,而不应仅用于推广应用。 - - - -</li> - <li> 请不要为了向用户宣传您的品牌而创建过多的通知。 - - 此类通知会让用户不满,从而很可能离您而去。提供少量更新信息并让用户保持与您的应用交互的最佳方式是开发一个小工具,让用户可以选择是否将其放在主屏幕上。 - - - - -</li> -</ul> - -<h2 style="clear:left" id="interacting_with_notifications">与通知交互 -</h2> - -<p>通知由状态栏中的图标指示,并且可以通过打开抽屉式通知栏进行访问。 - -</p> - -<p>触摸通知会打开相关联的应用并进入与通知匹配的详细内容。在通知上向左或向右滑动会将其从抽屉式通知栏中删除。 - -</p> - -<h3 id="ongoing_notifications">持续性通知</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/MusicPlayback.png" alt="" width="311px" /> - <p class="img-caption"> - 因播放音乐而持续显示的通知 - </p> -</div> -<p>持续性通知可让用户持续了解后台运行的进度。例如,音乐播放器在通知系统中通告当前播放的曲目,并继续进行播放,直至用户停止播放。 - - - -持续性通知也可为持续时间较长的任务(例如下载文件或视频编码之类的任务)向用户显示反馈。 - -用户无法手动从抽屉式通知栏中删除持续性通知。 -</p> - -<h3 id="ongoing_notifications">媒体播放</h3> -<p>在 Android 5.0 中,锁定屏幕不会为弃用的 -{@link android.media.RemoteControlClient} 类显示传输控件。但是它<em>确实</em>会显示通知,因此每个应用的播放通知现在是用户在锁屏状态控制播放的主要方式。 - -此行为可让应用更好地控制显示哪些按钮,这样,无论是否锁屏,都可以为用户提供一致的体验。 - - -</p> - -<h3 style="clear:both" -id="dialogs_and_toasts_are_for_feedback_not_notification">对话框和 Toast -</h3> - -<p>如果您的应用当前未显示在屏幕上,则不应创建对话框或 Toast。 -对话框或 Toast 应仅限用于即时响应用户在应用内部采取的操作。有关使用对话框和 Toast 的进一步指导,请参阅<a href="/design/patterns/confirming-acknowledging.html">确认和确知</a>。 - - - -</p> - -<h3>排名和排序</h3> - -<p>通知属于新闻,因此基本以时间倒序显示,并且会特别考虑应用规定的通知<a href="#correctly_set_and_manage_notification_priority">优先级</a>。 - - -</p> - -<p>通知是锁定屏幕的关键部分,并且在设备显示屏每次亮起时突出显示。 - -锁定屏幕上的空间有限,因此确定哪些通知最为紧急或最密切相关非常重要。 - -由于这个原因,Android 在处理通知时使用了更为精密的排序算法,考虑到以下因素: - -</p> - -<ul> - <li> 时间戳以及应用规定的优先级。</li> - <li> 通知是否最近以声音或振动形式告知过用户。 -(也就是说,如果手机刚发出了铃声,并且用户希望知道“刚才发生了什么?”,那么锁定屏幕应让用户一眼看到相应的通知。) - - -</li> - <li> 与使用 {@link android.app.Notification#EXTRA_PEOPLE} 的通知相关的任何人,尤其是加星标的联系人。 -</li> -</ul> - -<p>为了充分利用此排序功能,请专注于您希望建立的用户体验,而不是拘泥于列表上的某个特定项。 - -</p> - - <img src="{@docRoot}images/android-5.0/notifications/AntiSample3.png" alt="" width="700px" /> - - <p class="img-caption" style="margin-top:10px">Gmail 通知使用的是默认优先级,因此它们的顺序通常低于来自即时通讯应用(例如环聊)的消息,但是在有新邮件送达时会临时占位。 - - - - - </p> - - -<h3>在锁定屏幕上</h3> - -<p>由于通知在锁定屏幕上可见,所以用户隐私是特别重要的考虑事项。 - -通知通常包含敏感信息,并且不一定需要让所有拿起设备并打开显示屏的人看到。 - -</p> - -<ul> - <li> 对于配置了安全锁定屏幕(PIN 码、图案或密码)的设备,界面分为公用和私人部分。 -公用界面可显示在安全锁定屏幕上,因此任何人都可看见。 -私人界面是锁定屏幕背后的内容,只有在用户登录设备后才会显示。 -</li> -</ul> - -<h3>用户对显示在安全锁定屏幕上的信息的控制</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/LockScreen@2x.png" srcset="{@docRoot}images/android-5.0/notifications/LockScreen.png 1x" alt="" width="311px" /> - <p class="img-caption"> - 位于锁定屏幕上的通知,具有用户解锁设备后可显示的内容。 - </p> -</div> - -<p>在设置安全锁定屏幕时,用户可以选择从安全锁定屏幕隐藏敏感的详细信息。 -在这种情况下,系统 UI 会考虑通知的<em>可见性级别</em>,从而确定哪些内容可以安全地显示出来。 - -</p> -<p> 要控制可见性级别,可调用 <code><a -href="/reference/android/app/Notification.Builder.html#setVisibility(int)">Notification.Builder.setVisibility()</a></code>,然后指定以下值之一: - -</p> - -<ul> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PUBLIC">VISIBILITY_PUBLIC</a></code>。显示通知的完整内容。 - - 在未指定可见性的情况下,此设置是系统的默认设置。</li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PRIVATE">VISIBILITY_PRIVATE</a></code>。在锁定屏幕上,会显示通知的基本信息,包括其图标以及发布此通知的应用名称。 - -剩下的通知详细信息不会显示。需要注意的一些有用建议如下: - - <ul> - <li> 如果您希望为通知提供不同的公用版本,供系统显示在安全锁定屏幕上,可在 <code><a -href="/reference/android/app/Notification.html#publicVersion">Notification.publicVersion</a></code> 字段中提供替换通知对象。 - - - - <li> 该设置可让您的应用有机会创建有用内容的删减版本,但是不会显示个人信息。 -可参考短信应用的示例,这种应用的通知包括短信的文本以及发信者的姓名和联系人图标。该通知应为 <code>VISIBILITY_PRIVATE</code>,但是 <code>publicVersion</code> 仍然可以包含“有 3 条新消息”这样的有用信息,而不会提供其他识别性详细信息。 - - - - - </ul> - </li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_SECRET">Notification.VISIBILITY_SECRET</a></code>。仅显示最为精简的信息,甚至不包括通知图标。 -</li> -</ul> -<h2 style="clear:both" id="notifications_on_android_wear">Android Wear 上的通知 -</h2> - -<p>通知及其<em>操作</em>默认会和穿戴设备桥接。开发者可以控制哪些通知会从手机桥接至手表,反之亦然。 - - -开发者也可以控制哪些操作会进行桥接。如果您的应用包含无法通过单次点击完成的操作,则可以将这些操作隐藏在您的 Android Wear 设备通知中,或者考虑将它们连接至 Android Wear 设备应用,从而可让用户在其手表上完成操作。 - - - - - -</p> - -<h4>桥接通知和操作</h4> - -<p>连接的设备,例如手机,可将通知桥接至 Android Wear 设备,从而将通知显示在此处。 -与此相似,您也可以桥接操作,从而让用户可在 Android Wear 设备上直接操作通知。 -</p> - -<p><strong>桥接</strong></p> - -<ul> - <li> 新的即时通讯</li> - <li> 单次点击操作,例如 +1、赞、收藏</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/WearBasic.png" width="156px" height="156px" alt="" /> - -<p><strong>不要桥接</strong></p> - -<ul> - <li> 新收到的播客通知</li> - <li> 映射至手表上无法使用的功能的操作</li> -</ul> - - - -<p><h4>为 Android Wear 设备定义的独特操作</h4></p> - -<p>有些操作只能在 Android Wear 上执行。包括以下情况:</p> - -<ul> - <li> 例如“马上回来”这样的预设回复快速列表</li> - <li> 在手机上打开</li> - <li> 调出语音输入屏幕的“评论”或“回复”操作</li> - <li> 启动 Android Wear 专用应用的操作</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/ReplyAction.png" width="156px" height="156px" alt="" /> diff --git a/docs/html-intl/intl/zh-tw/design/patterns/notifications.jd b/docs/html-intl/intl/zh-tw/design/patterns/notifications.jd deleted file mode 100644 index 3e3f59c6d049..000000000000 --- a/docs/html-intl/intl/zh-tw/design/patterns/notifications.jd +++ /dev/null @@ -1,872 +0,0 @@ -page.title=通知 -page.tags="notifications","design","L" -@jd:body - - <a class="notice-developers" href="{@docRoot}training/notify-user/index.html"> - <div> - <h3>開發人員文件</h3> - <p>通知使用者</p> - </div> -</a> - -<a class="notice-designers" href="notifications_k.html"> - <div> - <h3>Android 4.4 及較早版本中的通知</h3> - </div> -</a> - -<!-- video box --> -<a class="notice-developers-video" href="https://www.youtube.com/watch?v=Uiq2kZ2JHVY"> -<div> - <h3>影片</h3> - <p>DevBytes:Android L 開發者預覽版中的通知</p> -</div> -</a> - -<style> - .col-5, .col-6, .col-7 { - margin-left:0px; - } -</style> - -<p>通知系統可以隨時知會使用者有關應用程式中的相關事件與及時事件,例如來自朋友的新聊天訊息。您可以將通知視為一種事件發生時警示使用者的新聞管道,或是在使用者沒注意時,記錄事件的日誌 — 並會視情況跨所有 Android 裝置且同步處理。 - - - - - -</p> - -<h4 id="New"><strong>Android 5.0 新功能</strong></h4> - -<p>在 Android 5.0 中,通知會透過結構化、視覺化和功能化的效果接收重要更新: -</p> - -<ul> - <li>通知已經有視覺方面的變更,與新的材料設計風格一致。 -</li> - <li> 現在可在裝置的鎖定螢幕上提供通知,而敏感內容仍可隱藏於其背後。 - -</li> - <li>當裝置於使用中收到高優先順序的通知時,會使用稱為預告 (heads-up) 通知的新格式。 -</li> - <li>雲端同步化通知:關閉您其中一部 Android 裝置的通知,隨之也會在其他裝置上關閉此通知。 - -</li> -</ul> - -<p class="note"><strong>注意:</strong>此版本 Android 中的通知設計和先前版本大相徑庭。 - -如需有關先前版本通知的設計資訊,請參閱 -<a href="./notifications_k.html">Android 4.4 及較早版本中的通知</a>。</p> - -<h2 id="Anatomy">通知的詳細分析</h2> - -<p>本節會重溫通知的基礎功能,以及其如何可在不同類型裝置上出現。 -</p> - -<h3 id="BaseLayout">基礎版面配置</h3> - -<p>至少,所有通知都必須包含一個基礎版面配置,它包含:</p> - -<ul> - <li> 通知的<strong>圖示</strong>。該圖示代表原始應用程式。如果應用程式會產生一種以上的通知類型,則圖示也有可能表示通知類型。 - - -</li> - <li> 一個通知<strong>標題</strong>和額外<strong>文字</strong>。 -</li> - <li> 一個<strong>時間戳記</strong>。</li> -</ul> - -<p>針對先前平台版本,使用 {@link android.app.Notification.Builder Notification.Builder} -所建立的通知其外觀與運作方式和在 Android 5.0 -中的一樣,只是在系統為您處理的方式上有一點樣式上的變更。 -如需更多有關 Android 先前版本通知的詳細資訊,請參閱 -<a href="./notifications_k.html">Android 4.4 及較早版本中的通知</a>。 -</p></p> - - - <img style="margin:20px 0 0 0" src="{@docRoot}images/android-5.0/notifications/basic_combo.png" alt="" width="700px" /> - - -<div style="clear:both;margin-top:20px"> - <p class="img-caption"> - 手持裝置通知的基礎版面配置 (左),以及穿戴裝置上的相同通知 (右),都帶有使用者相片及一個通知圖示 - - </p> - </div> - -<h3 id="ExpandedLayouts">擴充的版面配置</h3> - - -<p>您可以選擇到底要讓您應用程式的通知提供多詳細的資料。 -通知可以顯示訊息的前幾行,也可以顯示較大的影像預覽。 -此額外資訊可提供使用者更多內容,而且 — 在某些情況下 — 可讓使用者讀取完整訊息。 - - -使用者可以捏合縮放或執行單手指滑動,在精簡的版面配置與擴充的版面配置間切換。 - - - 對於單一事件通知,Android 提供三個擴充版面配置範本 -(文字、收件匣和影像),讓您可以在應用程式中使用。 -以下的影像顯示單一事件通知在手持裝置 (左) 和穿戴裝置 (右) 上的外觀。 - -</p> - -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/expandedtext_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/stack_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/ExpandedImage.png" - alt="" width="311px" height;="450px" /> - -<h3 id="actions" style="clear:both; margin-top:40px">動作</h3> - -<p>Android 支援可以在通知底端顯示的選用動作。透過動作,使用者可針對特定通知,從通知欄 (notification shade) 內處理最常見的工作,而無需開啟原始啟動的應用程式。這可加速互動,而且在配合滑動關閉 -(swipe-to-dismiss) -時,有助使用者專注於高重要性的通知。 - - - -</p> - - - <img src="{@docRoot}images/android-5.0/notifications/action_combo.png" alt="" width="700px" /> - - - -<p style="clear:both">明智地決定要在通知中要納入多少個動作。 -您納入的動作愈多,就會發現創造出愈複雜的通知。 -請納入最緊迫重要且有意義的動作,限制自己儘可能使用最少數目的動作。 - - -</p> - -<p>適合用於通知上的動作包含:</p> - -<ul> - <li> 必須是必要、頻繁且典型的想要顯示內容類型 - - <li> 可讓使用者快速完成工作 -</ul> - -<p>避免下列狀況:</p> - -<ul> - <li> 模稜兩可 - <li> 和通知的預設動作相同 (如「讀取」或「開啟」) - -</ul> - - - -<p>您最多可以指定三個動作,每個動作都由一個動作圖示與名稱組成。 - - 為簡單的基礎版面配置新增動作,可讓通知變得更具擴充性 --- -即使通知並未具備擴充的版面配置。由於動作只針對擴充的通知顯示,其他時候則隱藏,請確認使用者可從通知內呼叫的任何動作,也可以從關聯的應用程式中使用。 - - - - -</p> - -<h2 style="clear:left">預告通知</h2> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/hun-example.png" alt="" width="311px" /> - <p class="img-caption"> - 預告通知 (來電、高優先順序) -出現在沉浸式應用程式之上的範例 - - </p> -</div> - -<p>當高優先順序的通知到達 (如右) 時,會對使用者呈現很短的時間,且會顯示可能執行動作的擴充版面配置。 - -</p> -<p> 在這段時間之後,通知會退回至通知欄。 -如果通知的<a href="#correctly_set_and_manage_notification_priority">優先順序</a>被標記為「高」、「最大」或「全螢幕」,就會取得預告通知。 -</p> - -<p><b>預告通知的好範例</b></p> - -<ul> - <li> 使用裝置時有來電</li> - <li> 使用裝置時啟動鬧鐘功能</li> - <li> 新簡訊</li> - <li> 電池電力不足</li> -</ul> - -<h2 style="clear:both" id="guidelines">指導方針</h2> - - -<h3 id="MakeItPersonal">提供個人設定</h3> - -<p>針對由另一人傳送項目的通知 -(如郵件或狀態更新),使用 -{@link android.app.Notification.Builder#setLargeIcon setLargeIcon()} 納入對方提供的影像。也將對方的資訊附加至通知的中繼資料中 -(請參閱 {@link android.app.Notification#EXTRA_PEOPLE})。</p> - -<p>您通知的主要圖示仍會顯示,這樣使用者就可以將主要圖示與狀態列中的可見圖示關聯起來。 - -</p> - - -<img src="{@docRoot}images/android-5.0/notifications/Triggered.png" alt="" width="311px" /> -<p style="margin-top:10px" class="img-caption"> - 通知會顯示觸發通知的人及其傳送的內容。 -</p> - - -<h3 id="navigate_to_the_right_place">導覽至正確的地方</h3> - -<p>當輕觸通知的本文時 -(在動作按鈕之外),請將您的應用程式開啟至使用者可以檢視的地方,並根據通知中引用資料進行動作。 - -在多數情況下,這將是單一資料項目 (如訊息) 的詳細資料檢視,但如果通知被堆疊時,也可能會是概述檢視。 - -如果您的應用程式會將使用者帶到應用程式頂層之下的任何地方,則請將導覽過程插入應用程式的返回堆疊中,這可以讓使用者能夠按下系統的返回按鈕,返回至頂層。 - -如需詳細資訊,請見<a href="{@docRoot}design/patterns/navigation.html#into-your-app">導覽</a>設計模式中的「透過主螢幕視窗小工具和通知,導覽至您的應用程式」<em></em>。 - -</p> - -<h3 id="correctly_set_and_manage_notification_priority">正確設定和管理通知優先順序 - -</h3> - -<p>Android 支援對通知設定優先順序的旗標。此旗標可與其他通知旗標比較,影響通知顯示的位置,這有助於確保使用者一律會先看到最重要的通知。 - - -在發佈通知時,您可以從以下優先順序等級選擇: - -</p> -<table> - <tr> - <td class="tab0"> -<p><strong>優先順序</strong></p> -</td> - <td class="tab0"> -<p><strong>使用</strong></p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MAX</code></p> -</td> - <td class="tab1"> -<p>用於關鍵且緊急的通知,警示使用者注意此通知具時效性或必須在繼續特定工作前先解決的情況。 - - -</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>HIGH</code></p> -</td> - <td class="tab1"> -<p>主要用於重要通訊,例如內容為使用者特別感興趣的郵件或聊天事件。高優先順序通知會觸發預告通知的顯示。 - -</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>DEFAULT</code></p> -</td> - <td class="tab1"> -<p>用於不屬於此處所述任何其他優先事項類型的所有通知。</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>LOW</code></p> -</td> - <td class="tab1"> -<p>用於您希望使用者能夠被告知,但不那麼緊急的通知。 -低優先順序通知往往出現在清單的底端,因此適合於公共或間接的社交更新: - -使用者已要求針對這類事件通知,但這些通知一律不會優先於緊急或直接通訊。 - - -</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MIN</code></p> -</td> - <td class="tab1"> -<p>用於內容關聯或背景資訊,例如天氣資訊或內容關聯位置的資訊。最低優先順序通知不會出現在狀態列。 - -使用者會在展開通知欄時找到這些通知。 -</p> -</td> - </tr> -</table> - - -<h4 id="how_to_choose_an_appropriate_priority"><strong>如何選擇合適的優先順序</strong> - -</h4> - -<p><code>DEFAULT</code>、<code>HIGH</code> 和 <code>MAX</code> 為可中斷的優先順序等級,且有打斷使用者正進行動作的風險。 - -如要避免惹惱您應用程式的使用者,請將可中斷的優先順序保留給下列通知: -</p> - -<ul> - <li> 涉及另一人</li> - <li> 具時效性</li> - <li> 可能會立即變更使用者在現實世界中的行為</li> -</ul> - -<p>對使用者而言,設定為 <code>LOW</code> 和 <code>MIN</code> 的通知仍可能很有價值: -很多通知 -- 就算不是大多數 -- 並不需要使用者立即注意,或透過振動使用者的手腕加以提醒;但在使用者選擇查看通知時,這些通知仍會包含使用者覺得有價值的資訊。 - - -<code>LOW</code> 和 <code>MIN</code> - 優先順序通知的準則包含:</p> - -<ul> - <li> 不會牽涉到別人</li> - <li> 不具時效性</li> - <li> 包含使用者可能感興趣,但可能在空閒時才會瀏覽的內容 -</li> -</ul> - - - <img src="{@docRoot}images/android-5.0/notifications/notifications_pattern_priority.png" alt="" width="700" /> - - -<h3 style="clear:both" id="set_a_notification_category">設定通知類別 -</h3> - -<p>如果您的通知屬於某個預先定義的類別 -(詳見下列說明),則請據以指派。 -通知欄 (或任何其他通知接聽器) 等系統 UI -可能會使用此資訊,決定排名和篩選結果。 -</p> -<table> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_CALL">CATEGORY_CALL</a></code></p> -</td> - <td> -<p>來電 (語音或視訊) 或類似的同步化通訊要求 -</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_MESSAGE">CATEGORY_MESSAGE</a></code></p> -</td> - <td> -<p>傳入的直接訊息 (簡訊、即時訊息等)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EMAIL">CATEGORY_EMAIL</a></code></p> -</td> - <td> -<p>非同步大量郵件 (電子郵件)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EVENT">CATEGORY_EVENT</a></code></p> -</td> - <td> -<p>「行事曆」事件</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROMO">CATEGORY_PROMO</a></code></p> -</td> - <td> -<p>宣傳或廣告</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ALARM">CATEGORY_ALARM</a></code></p> -</td> - <td> -<p>鬧鐘或計時器</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROGRESS">CATEGORY_PROGRESS</a></code></p> -</td> - <td> -<p>長時間執行的背景操作其進度</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SOCIAL">CATEGORY_SOCIAL</a></code></p> -</td> - <td> -<p>社交網路或共用更新</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ERROR">CATEGORY_ERROR</a></code></p> -</td> - <td> -<p>背景操作或驗證狀態中的錯誤</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_TRANSPORT">CATEGORY_TRANSPORT</a></code></p> -</td> - <td> -<p>播放的媒體傳輸控制</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SYSTEM">CATEGORY_SYSTEM</a></code></p> -</td> - <td> -<p>系統或裝置狀態更新。保留供系統使用。</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SERVICE">CATEGORY_SERVICE</a></code></p> -</td> - <td> -<p>執行背景服務的表示</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_RECOMMENDATION">CATEGORY_RECOMMENDATION</a></code></p> -</td> - <td> -<p>針對單一件事的特定、及時建議。例如,新聞應用程式可能會想推薦其認為使用者下一步想要閱讀的新聞報導。 - -</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_STATUS">CATEGORY_STATUS</a></code></p> -</td> - <td> -<p>有關裝置或內容關聯狀態的進行中資訊</p> -</td> - </tr> -</table> - -<h3 id="summarize_your_notifications">概述您的通知</h3> - -<p>當您的應用程式嘗試傳送的通知,但已有類型相同的通知仍在等待中,則請針對應用程式將這些相同類型的通知合併為單一概述通知,而不要建立新物件。 - -</p> - -<p>概述通知會建立概述描述,並讓使用者瞭解特定種類的通知有多少數目正在等待處理。 - -</p> - -<div class="col-6"> - -<p><strong>不要這樣做</strong></p> - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Dont.png" alt="" width="311px" /> -</div> - -<div> -<p><strong>請這樣做</strong></p> - - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Do.png" alt="" width="311px" /> -</div> - -<p style="clear:left; padding-top:30px; padding-bottom:20px">您可以使用擴充摘要版面配置,針對組成概述的個別通知,提供更多詳細資料。 - -這種方法可讓使用者更能感覺出哪些通知正處於等待處理,以及是否夠有趣,以便在關聯應用程式中詳細閱讀。 - - - -</p> -<div class="col-6"> - <img src="{@docRoot}images/android-5.0/notifications/Stack.png" style="margin-bottom:20px" alt="" width="311px" /> - <p class="img-caption"> - 概述實際上是通知的展開和收縮 (使用 <code>InboxStyle</code>) - </p> -</div> - -<h3 style="clear:both" id="make_notifications_optional">讓通知成為可選用的 -</h3> - -<p>使用者應該總是能夠控制通知。讓使用者可以停用您應用程式的通知,或變更其警示屬性,如鬧鐘聲音或是否要使用振動,方法則是為您的應用程式設定新增通知設定項目。 - - - -</p> - -<h3 id="use_distinct_icons">使用易於分辨的的圖示</h3> -<p>使用者應該能瞄一下通知區域,即可以分辨哪些種類的通知目前正在等待處理。 - -</p> - -<div class="figure"> - <img src="{@docRoot}images/android-5.0/notifications/ProductIcons.png" alt="" width="420" /> -</div> - - <div><p><strong>請這樣做</strong></p> - <p>查看 Android 應用程式圖示, -Android 應用程式已為您的應用程式提供外觀易於分辨的通知圖示。 -</p> - - <p><strong>請這樣做</strong></p> - <p>針對小圖示使用<a href="/design/style/iconography.html#notification">通知圖示樣式</a>,針對您的動作列圖示使用 Material Light <a href="/design/style/iconography.html#action-bar">動作列圖示樣式</a>。 - - - -</p> -<p ><strong>請這樣做</strong></p> -<p >讓圖示保持看起來簡單的狀態,避免因過多的詳細資料造成使用者難以看清楚。 -</p> - - <div><p><strong>不要這樣做</strong></p> - <p>將任何額外的 -Alpha -(變暗或淡出) -置入您的小圖示和動作圖示之中;它們的邊緣可能會有反鋸齒狀,但因為 Android 使用這些圖示做為遮罩 -(也就是說,只使用 Alpha 通道),所以影像通常會以完全透明度來繪製。 -</p> - -</div> -<p style="clear:both"><strong>不要這樣做</strong></p> - -<p>使用顏色以區分您與其他人的應用程式。通知圖示應該只是個白色圖示透明背景的背景影像。 -</p> - - -<h3 id="pulse_the_notification_led_appropriately">可以調整通知 LED 適當開啟 -</h3> - -<p>許多 Android 裝置具備通知 LED,可用於當螢幕關閉時通知使用者有新事件。 - -優先順序等級為<code>MAX</code>、<code>HIGH</code> 和 <code>DEFAULT</code> 的通知, -應該要讓 LED 亮起,而只有低優先順序 (<code>LOW</code> 和 <code>MIN</code>) 的通知則不需要。 - -</p> - -<p>使用者對通知的控制應該延伸到 LED 上。當您使用 DEFAULT_LIGHTS,LED 會亮白色。 - -除非使用者已明確自訂通知,否則您的通知不應該使用其他顏色。 - -</p> - -<h2 id="building_notifications_that_users_care_about">建立使用者喜歡的通知 -</h2> - -<p>若要建立使用者喜歡的應用程式,精心設計您的通知非常重要。通知代表您應用程式的聲音,並有助於您應用程式的個性。 - - -非必要或非重要的通知會讓使用者不高興,這會讓他們覺得應用程式想要吸引注目不擇手段,所以請明智地使用通知。 - - -</p> - -<h3 id="when_to_display_a_notification">顯示通知的時機</h3> - -<p>若要建立人們喜歡使用的應用程式,重要的是要體認到使用者的注意與專注是必須加以保護的資源。 - -雖然 Android 的通知系統已重新設計,儘量降低通知對使用者注意力的影響。但仍然必須警覺,通知會中斷使用者的工作流程。在規劃您的通知時,請先自問:通知是否足夠重要到可以合理地中斷使用者。 - - - - - - -如果您不確定,則讓使用者可以使用您應用程式的通知設定,或調整通知優先順序旗標為 <code>LOW</code> 或 <code>MIN</code>,避免使用者在從事其他工作時因此分心。 - - - -</p> - - <img src="{@docRoot}images/android-5.0/notifications/TimeSensitive.png" alt="" width="311px" /> - <p style="margin-top:10px" class="img-caption"> - 具時效性的通知範例 - </p> - -<p>妥善規劃的應用程式只會在必要時才出現,但有幾個情況的確有益於應用程式透過無提示通知中斷使用者的行為。 -</p> - -<p>通知主要還是使用於<strong>具時效性時間的事件</strong>,特別是當這些同步事件<strong>涉及其他人</strong>的時候。 -比如說,傳入的聊天是通訊的即時、同步形式: - -另一個使用者正主動等待您的回應。 -「行事曆」事件是何時使用通知吸引使用者注意的另一個好例子,因為事件即將發生,而「行事曆」事件通常牽涉到其他人。 - - -</p> - -<h3 style="clear:both" id="when_not_to_display_a_notification">不顯示通知的時機 -</h3> - -<div class="figure" style="margin-top:60px"> - <img src="{@docRoot}images/android-5.0/notifications/AntiSample1.png" alt="" width="311px" /> -</div> - -<p>在許多其他情況下,通知並不適當:</p> - -<ul> - <li> 當通知並非直接針對使用者,或者資訊並非真正具時效性時,請避免通知使用者。 - -例如,來自社交網路的非同步與間接更新,通常不是即時中斷的好時機。 - - -對於重視這些狀況的使用者,可以讓他們自行選擇加入通知。 -</li> - <li> 如果相關的新資訊目前正在螢幕上,則不要建立另一個通知。 -反之,直接在前後關係中使用應用程式本身的 UI 通知使用者有新資訊。 - - - 例如,當使用者正與另一位使用者聊天時,聊天應用程式不應建立系統通知。 -</li> - <li> 如果應用程式或系統可以不干擾使用者而解決問題,就不要因為如儲存或同步化資訊,或更新應用程式等低層級的技術操作而中斷使用者活動。 - -</li> - <li> 如果可能的話,就讓應用程式能自行從錯誤恢復,在不需要使用者進行任何動作時,就不要告知他們錯誤而中斷使用者的活動。 - -</li> - <li> 不要建立無實質內容的通知,也不要建立內容僅是在廣告您應用程式的通知。 - -通知應該要能夠提供實用、及時的新資訊,而非只是為了啟動一個應用程式。 - -</li> - <li> 請不要為了讓您的品牌出現在使用者面前,而建立多餘的通知。 - - 這類通知會讓您的使用者感到失望並不願意使用您的應用程式。能夠提供少量的更新資訊並可以吸引使用者注意您應用程式的最佳方式,是開發一個小工具,讓使用者可以選擇放置在主畫面上。 - - - - -</li> -</ul> - -<h2 style="clear:left" id="interacting_with_notifications">與通知互動 -</h2> - -<p>通知可由狀態列上的圖示表示,並可以透過開啟通知匣來存取。 - -</p> - -<p>輕觸通知會開啟相關應用程式,顯示符合通知的詳細資料內容。對通知往左右滑動,可以將通知從通知匣中移除。 - -</p> - -<h3 id="ongoing_notifications">進行中通知</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/MusicPlayback.png" alt="" width="311px" /> - <p class="img-caption"> - 因為音樂播放的緣故所以有進行中通知 - </p> -</div> -<p>進行中通知可讓使用者得知在背景中正在進行程序的資訊。例如,音樂播放程式會在通知系統中宣告正在播放的曲目,除非使用者停止曲目,否則就會繼續宣告。 - - - -進行中通知也可以針對如下載檔案或編碼影片等耗時較長的工作,向使用者顯示目前進度。 - -使用者無法手動將進行中通知從通知匣移除。 -</p> - -<h3 id="ongoing_notifications">媒體播放</h3> -<p>在 Android 5.0 中,鎖定螢幕不會針對已過時的 -{@link android.media.RemoteControlClient} 類別,顯示傳輸控制項。但鎖定螢幕「的確」<em></em>會顯示通知,所以每個應用程式的播放通知,現在都已經是使用者從鎖定狀態控制播放的主要方法。 - -這個行為可讓應用程式進一步控制以何種方式顯示哪些按鈕,同時無論螢幕是否鎖定,都能為使用者提供一致性的體驗。 - - -</p> - -<h3 style="clear:both" -id="dialogs_and_toasts_are_for_feedback_not_notification">對話和快顯通知 -</h3> - -<p>您的應用程式目前若不在畫面上,就不應建立對話或快顯通知。 -對話或快顯通知只在使用者於您應用程式內採取動作時產生立即回應時才顯示。至於使用對話與快顯通知的進一步指引,請參閱<a href="/design/patterns/confirming-acknowledging.html">確認和確認完成</a>。 - - - -</p> - -<h3>排名和排序</h3> - -<p>通知就是新聞,所以基本上是以逆時間順序顯示,同時會針對應用程式指定的通知<a href="#correctly_set_and_manage_notification_priority">優先順序</a>,給與特殊考慮。 - - -</p> - -<p>通知是鎖定螢幕的重要部分,並會在裝置重新顯示螢幕時明確作用。 - -鎖定螢幕上的空間有限,所以更重要的是辨別出最緊急或相關的通知。 - -基於這個理由,Android 針對通知提供了更複雜的排序演算法,並同時考慮: - -</p> - -<ul> - <li> 時間戳記和應用程式指定的優先順序。</li> - <li> 通知最近是否以聲音或振動干擾使用者。 -(也就是說,如果電話剛發出一個聲響,而使用者想要知道「剛剛發生什麼事?」,鎖定螢幕應該以瞄一下就能取得通知的方式來回應使用者。 -) - -</li> - <li> 任何使用 {@link android.app.Notification#EXTRA_PEOPLE} 附加至該通知的人員,尤其是他們是否為標記星號的連絡人。 -</li> -</ul> - -<p>要善用這種排序,請著重於您想要建立的使用者體驗,而非著眼於清單上的任何特定排名位置。 - -</p> - - <img src="{@docRoot}images/android-5.0/notifications/AntiSample3.png" alt="" width="700px" /> - - <p class="img-caption" style="margin-top:10px">Gmail 通知使用預設的優先順序,所以通常排序低於像 Hangouts 等即時訊息應用程式,但當有新郵件進來時,會暫時立即提升。 - - - - - </p> - - -<h3>在鎖定螢幕上</h3> - -<p>由於通知可見於鎖定螢幕上,因此使用者隱私是特別重要的考量。 - -通知通常包含敏感資訊,而且不一定要顯示給拿起裝置並打開顯示的任何人。 - -</p> - -<ul> - <li> 針對具有安全鎖定螢幕 (PIN、圖案或密碼) 的裝置,介面有公用和私密兩部分。 -公用介面可以顯示在安全鎖定螢幕上,因此任何人都可看見。 -私密介面是鎖定螢幕背後的世界,只在使用者登入裝置時才會顯示。 -</li> -</ul> - -<h3>使用者控制安全鎖定螢幕上顯示的資訊</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/LockScreen@2x.png" srcset="{@docRoot}images/android-5.0/notifications/LockScreen.png 1x" alt="" width="311px" /> - <p class="img-caption"> - 鎖定螢幕上的通知,以及使用者解鎖裝置後顯示的內容。 - </p> -</div> - -<p>當設定安全鎖定螢幕時,使用者可以選擇隱藏來自安全鎖定螢幕的機密詳細資料。 -在這種情況下,系統 UI 會考慮通知的「可見度」<em></em>等級,判斷可以顯示何種內容。 - -</p> -<p> 如要控制可見度等級,可以呼叫 -<code><a -href="/reference/android/app/Notification.Builder.html#setVisibility(int)">Notification.Builder.setVisibility()</a></code>,並指定下列值之一: -</p> - -<ul> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PUBLIC">VISIBILITY_PUBLIC</a></code>。 -顯示通知的完整內容。 - 如果未指定可見度,則這會是系統預設值。</li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PRIVATE">VISIBILITY_PRIVATE</a></code>。 -在鎖定螢幕上,顯示這個通知存在的基本資訊, -包括通知圖示和發佈通知的應用程式。通知詳細資料的其他部分則不會顯示。 -但請記住的下列幾點: - <ul> - <li> 如果您想要提供您通知的不同公用版本, -以便顯示在安全鎖定螢幕上, -請在 <code><a -href="/reference/android/app/Notification.html#publicVersion">Notification.publicVersion</a></code> -欄位中提供一個取代的「通知」物件。 - <li> 此設定可以讓您的應用程式有機會建立內容的改編版本,非常實用但卻不會透露個人資訊。 -考慮簡訊應用程式的例子, -其通知包含簡訊的文字和傳送者的姓名與連絡人圖示。 -此通知應該是 <code>VISIBILITY_PRIVATE</code>,但 <code>publicVersion</code> 仍包含像「3 個新訊息」等實用資訊, -但卻又不提供任何其他可用來識別的詳細資料。 - - </ul> - </li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_SECRET">Notification.VISIBILITY_SECRET</a></code>。僅顯示最起碼的資訊, -甚至連通知圖示都排除。</li> -</ul> -<h2 style="clear:both" id="notifications_on_android_wear">Android Wear 上的通知 -</h2> - -<p>預設情況下,通知和其<em>動作</em>會橋接至穿戴裝置。 -開發人員可以控制哪些通知可從電話橋接至手錶上, -反之亦然。 -開發人員還可以控制哪些動作可以橋接。如果您的 -應用程式包含 -無法以單一點選完成的動作, -請在您的穿戴通知上隱藏這些動作 -,或考慮將其連結至穿戴應用程式, -讓使用者可以在手錶上完成動作。 -</p> - -<h4>橋接通知和動作</h4> - -<p>例如電話等已連線的裝置, -可以橋接通知至穿戴裝置,讓通知可以在該處顯示。同樣的,也可以橋接動作, -這樣使用者就可以直接從穿戴裝置對通知執行動作。</p> - -<p><strong>橋接</strong></p> - -<ul> - <li> 新的即時訊息</li> - <li> 例如 +1 等單點選動作,像 Heart</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/WearBasic.png" width="156px" height="156px" alt="" /> - -<p><strong>請勿橋接</strong></p> - -<ul> - <li> 新到播客的通知</li> - <li> 對應至手錶上不可能執行的動作</li> -</ul> - - - -<p><h4>要在穿戴裝置上定義的獨特動作</h4></p> - -<p>有些動作只能在穿戴裝置上執行。這些動作包含:</p> - -<ul> - <li> 罐頭回應的快速清單,例如「會馬上回來」</li> - <li> 在手機上開啟</li> - <li> 帶出語音輸入畫面的「註解」或「回覆」動作</li> - <li> 啟動穿戴裝置特定的應用程式動作</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/ReplyAction.png" width="156px" height="156px" alt="" /> diff --git a/docs/html/_redirects.yaml b/docs/html/_redirects.yaml index 4cfe8087a1ef..7391af896a51 100644 --- a/docs/html/_redirects.yaml +++ b/docs/html/_redirects.yaml @@ -23,6 +23,8 @@ redirects: to: /studio/debug/index.html - from: /sdk/compatibility-library.html to: /topic/libraries/support-library/index.html +- from: /billions + to: /topic/billions/index.html - from: /tools/extras/support-library.html to: /topic/libraries/support-library/index.html - from: /training/basics/fragments/support-lib.html @@ -321,6 +323,8 @@ redirects: to: https://www.google.com/design/spec/layout/principles.html - from: /design/patterns/navigation-drawer.html to: https://www.google.com/design/spec/patterns/navigation-drawer.html +- from: /design/patterns/notifications.html + to: https://material.google.com/patterns/notifications.html - from: /design/patterns/selection.html to: https://www.google.com/design/spec/patterns/selection.html - from: /design/patterns/settings.html @@ -421,6 +425,8 @@ redirects: to: /training/implementing-navigation/lateral.html - from: /training/cloudsync/aesync.html to: /google/gcm/index.html +- from: /training/cloudsync/index.html + to: /training/backup/index.html - from: /training/basics/location/ to: /training/location/ - from: /training/monetization/index.html @@ -473,6 +479,14 @@ redirects: to: /distribute/stories/index.html - from: /distribute/stories/tablets.html to: /distribute/stories/index.html +- from: /distribute/stories/glu-dh.html + to: /distribute/stories/games/glu-dh.html +- from: /distribute/stories/apps/tapps.html + to: /distribute/stories/games/tapps.html +- from: /distribute/stories/apps/upbeat-games.html + to: /distribute/stories/games/upbeat-games.html +- from: /distribute/stories/games/two-dots.html + to: /distribute/stories/games/dots.html - from: /distribute/googleplay/edu/index.html to: /distribute/googleplay/edu/about.html - from: /distribute/googleplay/edu/contact.html @@ -805,8 +819,8 @@ redirects: to: /about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client - from: /shareables/... to: https://commondatastorage.googleapis.com/androiddevelopers/shareables/... -- from: /downloads/ - to: https://commondatastorage.googleapis.com/androiddevelopers/ +- from: /downloads/... + to: https://commondatastorage.googleapis.com/androiddevelopers/... - from: /training/performance/battery/network/action-any-traffic.html to: /topic/performance/power/network/action-any-traffic.html - from: /training/performance/battery/network/action-app-traffic.html diff --git a/docs/html/about/dashboards/index.jd b/docs/html/about/dashboards/index.jd index 3cbfde9cc386..f5d23e8b4032 100644 --- a/docs/html/about/dashboards/index.jd +++ b/docs/html/about/dashboards/index.jd @@ -59,7 +59,7 @@ Platform Versions</a>.</p> </div> -<p style="clear:both"><em>Data collected during a 7-day period ending on July 11, 2016. +<p style="clear:both"><em>Data collected during a 7-day period ending on August 1, 2016. <br/>Any versions with less than 0.1% distribution are not shown.</em> </p> @@ -81,7 +81,7 @@ Screens</a>.</p> </div> -<p style="clear:both"><em>Data collected during a 7-day period ending on July 11, 2016. +<p style="clear:both"><em>Data collected during a 7-day period ending on August 1, 2016. <br/>Any screen configurations with less than 0.1% distribution are not shown.</em></p> @@ -101,7 +101,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%7CGL%203.1&chf=bg%2Cs%2C00000000&chd=t%3A47.5%2C41.9%2C10.6&chco=c4df9b%2C6fad0c&cht=p&chs=400x250"> +src="//chart.googleapis.com/chart?chl=GL%202.0%7CGL%203.0%7CGL%203.1&chf=bg%2Cs%2C00000000&chd=t%3A46.0%2C42.6%2C11.4&chco=c4df9b%2C6fad0c&cht=p&chs=400x250"> <p>To declare which version of OpenGL ES your application requires, you should use the {@code android:glEsVersion} attribute of the <a @@ -119,21 +119,21 @@ uses.</p> </tr> <tr> <td>2.0</td> -<td>47.5%</td> +<td>46.0%</td> </tr> <tr> <td>3.0</td> -<td>41.9%</td> +<td>42.6%</td> </tr> <tr> <td>3.1</td> -<td>10.6%</td> +<td>11.4%</td> </tr> </table> -<p style="clear:both"><em>Data collected during a 7-day period ending on July 11, 2016</em></p> +<p style="clear:both"><em>Data collected during a 7-day period ending on August 1, 2016</em></p> @@ -147,19 +147,19 @@ var SCREEN_DATA = "Large": { "hdpi": "0.5", "ldpi": "0.2", - "mdpi": "4.4", + "mdpi": "4.3", "tvdpi": "2.1", "xhdpi": "0.5" }, "Normal": { - "hdpi": "40.9", - "mdpi": "4.1", + "hdpi": "40.0", + "mdpi": "3.8", "tvdpi": "0.1", - "xhdpi": "26.3", - "xxhdpi": "15.1" + "xhdpi": "27.3", + "xxhdpi": "15.5" }, "Small": { - "ldpi": "1.9" + "ldpi": "1.8" }, "Xlarge": { "hdpi": "0.3", @@ -167,8 +167,8 @@ var SCREEN_DATA = "xhdpi": "0.7" } }, - "densitychart": "//chart.googleapis.com/chart?chco=c4df9b%2C6fad0c&chd=t%3A2.1%2C11.4%2C2.2%2C41.7%2C27.5%2C15.1&chf=bg%2Cs%2C00000000&chl=ldpi%7Cmdpi%7Ctvdpi%7Chdpi%7Cxhdpi%7Cxxhdpi&chs=400x250&cht=p", - "layoutchart": "//chart.googleapis.com/chart?chco=c4df9b%2C6fad0c&chd=t%3A3.9%2C7.7%2C86.5%2C1.9&chf=bg%2Cs%2C00000000&chl=Xlarge%7CLarge%7CNormal%7CSmall&chs=400x250&cht=p" + "densitychart": "//chart.googleapis.com/chart?chd=t%3A2.0%2C11.0%2C2.2%2C40.8%2C28.5%2C15.5&chf=bg%2Cs%2C00000000&chl=ldpi%7Cmdpi%7Ctvdpi%7Chdpi%7Cxhdpi%7Cxxhdpi&cht=p&chs=400x250&chco=c4df9b%2C6fad0c", + "layoutchart": "//chart.googleapis.com/chart?chd=t%3A3.9%2C7.6%2C86.7%2C1.8&chf=bg%2Cs%2C00000000&chl=Xlarge%7CLarge%7CNormal%7CSmall&cht=p&chs=400x250&chco=c4df9b%2C6fad0c" } ]; @@ -176,7 +176,7 @@ var SCREEN_DATA = var VERSION_DATA = [ { - "chart": "//chart.googleapis.com/chart?chco=c4df9b%2C6fad0c&chd=t%3A0.1%2C1.9%2C1.7%2C17.8%2C30.2%2C35.1%2C13.3&chf=bg%2Cs%2C00000000&chl=Froyo%7CGingerbread%7CIce%20Cream%20Sandwich%7CJelly%20Bean%7CKitKat%7CLollipop%7CMarshmallow&chs=500x250&cht=p", + "chart": "//chart.googleapis.com/chart?chd=t%3A0.1%2C1.7%2C1.6%2C16.7%2C29.2%2C35.5%2C15.2&chf=bg%2Cs%2C00000000&chl=Froyo%7CGingerbread%7CIce%20Cream%20Sandwich%7CJelly%20Bean%7CKitKat%7CLollipop%7CMarshmallow&cht=p&chs=500x250&chco=c4df9b%2C6fad0c", "data": [ { "api": 8, @@ -186,47 +186,47 @@ var VERSION_DATA = { "api": 10, "name": "Gingerbread", - "perc": "1.9" + "perc": "1.7" }, { "api": 15, "name": "Ice Cream Sandwich", - "perc": "1.7" + "perc": "1.6" }, { "api": 16, "name": "Jelly Bean", - "perc": "6.4" + "perc": "6.0" }, { "api": 17, "name": "Jelly Bean", - "perc": "8.8" + "perc": "8.3" }, { "api": 18, "name": "Jelly Bean", - "perc": "2.6" + "perc": "2.4" }, { "api": 19, "name": "KitKat", - "perc": "30.1" + "perc": "29.2" }, { "api": 21, "name": "Lollipop", - "perc": "14.3" + "perc": "14.1" }, { "api": 22, "name": "Lollipop", - "perc": "20.8" + "perc": "21.4" }, { "api": 23, "name": "Marshmallow", - "perc": "13.3" + "perc": "15.2" } ] } diff --git a/docs/html/about/versions/android-5.0-changes.jd b/docs/html/about/versions/android-5.0-changes.jd index 25d253fb8d2f..0e9dac502432 100644 --- a/docs/html/about/versions/android-5.0-changes.jd +++ b/docs/html/about/versions/android-5.0-changes.jd @@ -105,7 +105,9 @@ Behavior on the Android Runtime (ART)</a>. Pay particular attention if:</p> <p>Make sure your notifications take these Android 5.0 changes into account. To learn more about designing your notifications for Android 5.0 and higher, - see the <a href="{@docRoot}design/patterns/notifications.html">notifications design guide</a>. + see the <a + href="https://material.google.com/patterns/notifications.html">notifications + design guide</a>. </p> <h3 id="NotificationsMaterialDesignStyle">Material design style</h3> diff --git a/docs/html/auto/images/logos/auto/gmc.png b/docs/html/auto/images/logos/auto/gmc.png Binary files differindex ab36da152944..ee0c1bf68bf7 100644 --- a/docs/html/auto/images/logos/auto/gmc.png +++ b/docs/html/auto/images/logos/auto/gmc.png diff --git a/docs/html/auto/images/logos/auto/koenigsegg.png b/docs/html/auto/images/logos/auto/koenigsegg.png Binary files differnew file mode 100644 index 000000000000..f2cf17ba828c --- /dev/null +++ b/docs/html/auto/images/logos/auto/koenigsegg.png diff --git a/docs/html/auto/images/logos/auto/lada.png b/docs/html/auto/images/logos/auto/lada.png Binary files differindex d1724601a98e..77bb5a447026 100644 --- a/docs/html/auto/images/logos/auto/lada.png +++ b/docs/html/auto/images/logos/auto/lada.png diff --git a/docs/html/auto/images/logos/auto/opel.png b/docs/html/auto/images/logos/auto/opel.png Binary files differindex fcb70402b30c..ecae4dba48d3 100644 --- a/docs/html/auto/images/logos/auto/opel.png +++ b/docs/html/auto/images/logos/auto/opel.png diff --git a/docs/html/auto/images/logos/auto/peugeot.png b/docs/html/auto/images/logos/auto/peugeot.png Binary files differindex d76a4bc09e17..e2bce369c3ab 100644 --- a/docs/html/auto/images/logos/auto/peugeot.png +++ b/docs/html/auto/images/logos/auto/peugeot.png diff --git a/docs/html/auto/images/logos/auto/renault.png b/docs/html/auto/images/logos/auto/renault.png Binary files differindex 297043068e03..c676bd1ed01e 100644 --- a/docs/html/auto/images/logos/auto/renault.png +++ b/docs/html/auto/images/logos/auto/renault.png diff --git a/docs/html/auto/images/logos/auto/seat.png b/docs/html/auto/images/logos/auto/seat.png Binary files differindex 9802ccf8b6b2..ddd9d054eab0 100644 --- a/docs/html/auto/images/logos/auto/seat.png +++ b/docs/html/auto/images/logos/auto/seat.png diff --git a/docs/html/auto/images/logos/auto/ssangyong.png b/docs/html/auto/images/logos/auto/ssangyong.png Binary files differindex 9e0f1177b8d2..c50237a9bc11 100644 --- a/docs/html/auto/images/logos/auto/ssangyong.png +++ b/docs/html/auto/images/logos/auto/ssangyong.png diff --git a/docs/html/auto/images/logos/auto/tata.png b/docs/html/auto/images/logos/auto/tata.png Binary files differindex dfc4a5f8eed8..fc405446e97f 100644 --- a/docs/html/auto/images/logos/auto/tata.png +++ b/docs/html/auto/images/logos/auto/tata.png diff --git a/docs/html/auto/images/logos/auto/volvo.png b/docs/html/auto/images/logos/auto/volvo.png Binary files differindex 683af2644ef8..4d39db01e1d0 100644 --- a/docs/html/auto/images/logos/auto/volvo.png +++ b/docs/html/auto/images/logos/auto/volvo.png diff --git a/docs/html/auto/index.jd b/docs/html/auto/index.jd index 167ed7b8bd45..e6fde38342d0 100644 --- a/docs/html/auto/index.jd +++ b/docs/html/auto/index.jd @@ -499,6 +499,12 @@ nonavpage=true </div> <div class="cols cols-leftp"> <div class="col-5"> + <a href=" http://koenigsegg.com/"> + <img src="/auto/images/logos/auto/koenigsegg.png" + width="120" height="120" class="img-logo" /> + </a> + </div> + <div class="col-5"> <a href=" http://www.lada.ru/en/"> <img src="{@docRoot}auto/images/logos/auto/lada.png" width="120" height="120" class="img-logo" /> @@ -516,14 +522,14 @@ nonavpage=true width="120" height="120" class="img-logo" /> </a> </div> + </div> + <div class="cols cols-leftp"> <div class="col-5"> <a href=" http://www.lincoln.com/"> <img src="{@docRoot}auto/images/logos/auto/lincoln.png" width="120" height="120" class="img-logo" /> </a> </div> - </div> - <div class="cols cols-leftp"> <div class="col-5"> <a href="http://www.mahindra.com/"> <img src="{@docRoot}auto/images/logos/auto/mahindra.png" @@ -542,15 +548,14 @@ nonavpage=true width="120" height="120" class="img-logo" /> </a> </div> - + </div> + <div class="cols cols-leftp"> <div class="col-5"> <a href="http://www.mercedes-benz.com/"> <img src="{@docRoot}auto/images/logos/auto/mbenz.png" width="120" height="120" class="img-logo" /> </a> </div> - </div> - <div class="cols cols-leftp"> <div class="col-5"> <a href="http://www.mitsubishi-motors.com/"> <img src="{@docRoot}auto/images/logos/auto/mitsubishi.png" @@ -569,16 +574,14 @@ nonavpage=true width="120" height="120" class="img-logo" /> </a> </div> - + </div> + <div class="cols cols-leftp"> <div class="col-5"> <a href="http://www.peugeot.com/"> <img src="{@docRoot}auto/images/logos/auto/peugeot.png" width="120" height="120" class="img-logo" /> </a> </div> - </div> - - <div class="cols cols-leftp"> <div class="col-5"> <a href="http://www.ramtrucks.com/"> <img src="{@docRoot}auto/images/logos/auto/ram.png" @@ -597,15 +600,14 @@ nonavpage=true width="120" height="120" class="img-logo" /> </a> </div> - + </div> + <div class="cols cols-leftp"> <div class="col-5"> <a href="http://www.seat.com/"> <img src="{@docRoot}auto/images/logos/auto/seat.png" width="120" height="120" class="img-logo" /> </a> </div> - </div> - <div class="cols cols-leftp"> <div class="col-5"> <a href="http://www.skoda-auto.com/"> <img src="{@docRoot}auto/images/logos/auto/skoda.png" @@ -624,16 +626,14 @@ nonavpage=true width="120" height="120" class="img-logo" /> </a> </div> - + </div> + <div class="cols cols-leftp"> <div class="col-5"> <a href="http://www.globalsuzuki.com/automobile/"> <img src="{@docRoot}auto/images/logos/auto/suzuki.png" width="120" height="120" class="img-logo" /> </a> </div> - </div> - - <div class="cols cols-leftp"> <div class="col-5"> <a href="http://www.tatamotors.com/"> <img src="{@docRoot}auto/images/logos/auto/tata.png" @@ -652,8 +652,8 @@ nonavpage=true width="120" height="120" class="img-logo" /> </a> </div> - - + </div> + <div class="cols cols-leftp"> <div class="col-5"> <a href="http://www.volvocars.com/intl"> <img src="{@docRoot}auto/images/logos/auto/volvo.png" @@ -661,7 +661,6 @@ nonavpage=true </a> </div> </div> - </div> </div> <div class="landing-section landing-red-background"> diff --git a/docs/html/design/_book.yaml b/docs/html/design/_book.yaml index df5406f269dd..18b47194265f 100644 --- a/docs/html/design/_book.yaml +++ b/docs/html/design/_book.yaml @@ -90,23 +90,6 @@ toc: value: 使用返回和向上导航 - name: zh-tw-lang value: 使用 [返回] 及 [上一層] 導覽 - - title: Notifications - path: /design/patterns/notifications.html - path_attributes: - - name: es-lang - value: Notificaciones - - name: ja-lang - value: 通知 - - name: ko-lang - value: 알림 - - name: pt-br-lang - value: Notificações - - name: ru-lang - value: Уведомления - - name: zh-cn-lang - value: 通知 - - name: zh-tw-lang - value: 通知 - title: Widgets path: /design/patterns/widgets.html - title: Swipe Views diff --git a/docs/html/design/design_toc.cs b/docs/html/design/design_toc.cs index a837a04ffb8b..c1f3c3bda00b 100644 --- a/docs/html/design/design_toc.cs +++ b/docs/html/design/design_toc.cs @@ -70,15 +70,6 @@ zh-tw-lang="使用 [返回] 及 [上一層] 導覽"> Navigation</a></li> - <li><a href="<?cs var:toroot ?>design/patterns/notifications.html" - es-lang="Notificaciones" - ja-lang="通知" - ko-lang="알림" - pt-br-lang="Notificações" - ru-lang="Уведомления" - zh-cn-lang="通知" - zh-tw-lang="通知"> - Notifications</a></li> <li><a href="<?cs var:toroot ?>design/patterns/widgets.html">Widgets</a></li> <li><a href="<?cs var:toroot ?>design/patterns/swipe-views.html">Swipe Views</a></li> <li><a href="<?cs var:toroot ?>design/patterns/fullscreen.html">Full Screen</a></li> diff --git a/docs/html/design/handhelds/index.jd b/docs/html/design/handhelds/index.jd index 4a4526cb21b8..cf224aeb6484 100755 --- a/docs/html/design/handhelds/index.jd +++ b/docs/html/design/handhelds/index.jd @@ -92,7 +92,8 @@ to allow the user to enjoy full screen content without distraction.</p> <p>Notifications are brief messages that users can access at any time from the status bar. They provide updates, reminders, or information that's important, but not critical enough to warrant interrupting the user. Open the notifications drawer by swiping down on the status bar. Touching a -notification opens the associated app. <a href="{@docRoot}design/patterns/notifications.html">More on Notifications</a></p> +notification opens the associated app. <a +href="https://material.google.com/patterns/notifications.html">More on Notifications</a></p> <div class="cols"> <div class="col-4"> diff --git a/docs/html/design/patterns/new.jd b/docs/html/design/patterns/new.jd index df4c2ede187e..4bd3aa3ad02f 100755 --- a/docs/html/design/patterns/new.jd +++ b/docs/html/design/patterns/new.jd @@ -18,7 +18,7 @@ implement material design patterns in your apps.</p> <h3>Notifications</h3> -<p><a href="{@docRoot}design/patterns/notifications.html">Notifications</a> receive important +<p><a href="https://material.google.com/patterns/notifications.html">Notifications</a> receive important updates in Android 5.0, with material design visual changes, notification availability in the lockscreen, priority notifications, and cloud-synced notifications.</p> @@ -124,7 +124,7 @@ lockscreen, priority notifications, and cloud-synced notifications.</p> <p>The base notification layout has not changed, so app notifications designed for versions earlier than Jelly Bean still look and work the same. Check the updated <a - href="{@docRoot}design/patterns/notifications.html">Notifications</a> page for + href="https://material.google.com/patterns/notifications.html">Notifications</a> page for more details.</p> </div> <div class="col-6"> diff --git a/docs/html/design/patterns/notifications.jd b/docs/html/design/patterns/notifications.jd deleted file mode 100644 index 844c3b6b95f3..000000000000 --- a/docs/html/design/patterns/notifications.jd +++ /dev/null @@ -1,895 +0,0 @@ -page.title=Notifications -page.tags="notifications","design" -@jd:body - - <a class="notice-developers right" href="{@docRoot}training/notify-user/index.html"> - <div> - <h3>Developer Docs</h3> - <p>Notifying the User</p> - </div> -</a> - -<a class="notice-designers right" href="notifications_k.html"> - <div> - <h3>Notifications in Android 4.4 and Lower</h3> - </div> -</a> - -<!-- video box --> -<a class="notice-developers-video right" href="https://www.youtube.com/watch?v=Uiq2kZ2JHVY"> -<div> - <h3>Video</h3> - <p>DevBytes: Notifications in the Android L Developer Preview</p> -</div> -</a> - -<style> - .col-5, .col-6, .col-7 { - margin-left:0px; - } -</style> - -<p>The notification system allows users to keep informed about relevant and -timely -events in your app, such as new chat messages from a friend or a calendar event. -Think of notifications as a news channel that alerts the user to important -events as -they happen or a log that chronicles events while the user is not paying -attention—and one that is synced as appropriate across all their Android devices.</p> - -<h4 id="New"><strong>New in Android 5.0</strong></h4> - -<p>In Android 5.0, notifications receive important updates: structurally, -visually, and functionally:</p> - -<ul> - <li>Notifications have undergone visual changes consistent with the new -material design theme.</li> - <li> Notifications are now available on the device lock screen, while -sensitive content can still - be hidden behind it.</li> - <li>High-priority notifications received while the device is in use now use a new format called - heads-up notifications.</li> - <li>Cloud-synced notifications: Dismissing a notification on one of your -Android devices dismisses it - on the others, as well.</li> -</ul> - -<p class="note"><strong>Note:</strong> Notification design in this version of -Android is a significant -departure from that of previous versions. For information about notification design in previous -versions, see <a href="./notifications_k.html">Notifications in Android 4.4 and lower</a>.</p> - -<h2 id="Anatomy">Anatomy of a Notification</h2> - -<p>This section goes over basic parts of a notification and how they can -appear on different types of devices.</p> - -<h3 id="BaseLayout">Base layout</h3> - -<p>At a minimum, all notifications consist of a base layout, including:</p> - -<ul> - <li> The notification's <strong>icon</strong>. The icon symbolizes the -originating app. It may also - potentially indicate notification type if the app generates more than one -type.</li> - <li> A notification <strong>title</strong> and additional -<strong>text</strong>.</li> - <li> A <strong>timestamp</strong>.</li> -</ul> - -<p>Notifications created with {@link android.app.Notification.Builder Notification.Builder} -for previous platform versions look and work the same in Android -5.0, with only minor stylistic changes that the system handles -for you. For more information about notifications on previous versions of -Android, see -<a href="./notifications_k.html">Notifications in Android 4.4 and lower</a>.</p></p> - - - <img style="margin:20px 0 0 0" -src="{@docRoot}images/android-5.0/notifications/basic_combo.png" - alt="" width="700px" /> - - -<div style="clear:both;margin-top:20px"> - <p class="img-caption"> - Base layout of a handheld notification (left) and the same notification on Wear (right), - with a user photo and a notification icon - </p> - </div> - -<h3 id="ExpandedLayouts">Expanded layouts</h3> - - -<p>You can choose how much detail your app's notifications should -provide. They can show the first -few lines of a message or show a larger image preview. The additional -information provides the user with more -context, and—in some cases—may allow the user to read a message in its -entirety. The user can -pinch-zoom or perform a single-finger glide to toggle between compact -and expanded layouts. - For single-event notifications, Android provides three expanded layout -templates (text, inbox, and - image) for you to use in your application. The following images show you how -single-event notifications look on - handhelds (left) and wearables (right).</p> - -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/expandedtext_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/stack_combo.png" - alt="" width="700px" height;="284px" /> -<img style="margin-top:30px" -src="{@docRoot}images/android-5.0/notifications/ExpandedImage.png" - alt="" width="311px" height;="450px" /> - -<h3 id="actions" style="clear:both; margin-top:40px">Actions</h3> - -<p>Android supports optional actions that are displayed at the bottom -of the notification. -With actions, users can handle the most common tasks for a particular -notification from within the notification shade without having to open the -originating application. -This speeds up interaction and, in conjunction with swipe-to-dismiss, helps users focus on -notifications that matter to them.</p> - - - <img src="{@docRoot}images/android-5.0/notifications/action_combo.png" - alt="" width="700px" /> - - - -<p style="clear:both">Be judicious with how many actions you include with a -notification. The more -actions you include, the more cognitive complexity you create. Limit yourself -to the smallest number -of actions possible by only including the most imminently important and -meaningful actions.</p> - -<p>Good candidates for actions on notifications are actions that:</p> - -<ul> - <li> Are essential, frequent, and typical for the content type you're -displaying - <li> Allow the user to accomplish tasks quickly -</ul> - -<p>Avoid actions that are:</p> - -<ul> - <li> Ambiguous - <li> The same as the default action of the notification (such as "Read" or -"Open") -</ul> - - - -<p>You can specify a maximum of three actions, each consisting of an action -icon and name. - Adding actions to a simple base layout makes the notification expandable, -even if the - notification doesn't have an expanded layout. Since actions are only shown for -expanded - notifications and are otherwise hidden, make sure that any action a -user can invoke from - a notification is available from within the associated application, as -well.</p> - -<h2 style="clear:left">Heads-up Notification</h2> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/hun-example.png" - alt="" width="311px" /> - <p class="img-caption"> - Example of a heads-up notification (incoming phone call, high priority) -appearing on top of an - immersive app - </p> -</div> - -<p>When a high-priority notification arrives (see right), it is presented -to users for a -short period of time with an expanded layout exposing possible actions.</p> -<p> After this period of time, the notification retreats to the notification -shade. If a notification's <a href="#correctly_set_and_manage_notification_priority">priority</a> is -flagged as High, Max, or full-screen, it gets a heads-up notification.</p> - -<p><b>Good examples of heads-up notifications</b></p> - -<ul> - <li> Incoming phone call when using a device</li> - <li> Alarm when using a device</li> - <li> New SMS message</li> - <li> Low battery</li> -</ul> - -<h2 style="clear:both" id="guidelines">Guidelines</h2> - - -<h3 id="MakeItPersonal">Make it personal</h3> - -<p>For notifications of items sent by another person (such as a message or -status update), include that person's image using -{@link android.app.Notification.Builder#setLargeIcon setLargeIcon()}. Also attach information about -the person to the notification's metadata (see {@link android.app.Notification#EXTRA_PEOPLE}).</p> - -<p>Your notification's main icon is still shown, so the user can associate -it with the icon -visible in the status bar.</p> - - -<img src="{@docRoot}images/android-5.0/notifications/Triggered.png" - alt="" width="311px"/> -<p style="margin-top:10px" class="img-caption"> - Notification that shows the person who triggered it and the content they sent. -</p> - - -<h3 id="navigate_to_the_right_place">Navigate to the right place</h3> - -<p>When the user touches the body of a notification (outside of the action -buttons), open your app -to the place where the user can view and act upon the data referenced in the -notification. In most cases, this will be the detailed view of a single data item such as a message, -but it might also be a -summary view if the notification is stacked. If your app takes the -user anywhere below your app's top level, insert navigation into your app's back stack so that the -user can press the system back button to return to the top level. For more information, see -<em>Navigation into Your App via Home Screen Widgets and Notifications</em> in the <a -href="{@docRoot}design/patterns/navigation.html#into-your-app">Navigation</a> -design pattern.</p> - -<h3 id="correctly_set_and_manage_notification_priority">Correctly set and -manage notification -priority</h3> - -<p>Android supports a priority flag for notifications. This flag allows you to -influence where your notification appears, relative to other notifications, and -helps ensure -that users always see their most important notifications first. You can choose -from the -following priority levels when posting a notification:</p> -<table> - <tr> - <td class="tab0"> -<p><strong>Priority</strong></p> -</td> - <td class="tab0"> -<p><strong>Use</strong></p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MAX</code></p> -</td> - <td class="tab1"> -<p>Use for critical and urgent notifications that alert the user to a condition -that is -time-critical or needs to be resolved before they can continue with a -particular task.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>HIGH</code></p> -</td> - <td class="tab1"> -<p>Use primarily for important communication, such as message or chat -events with content that is particularly interesting for the user. -High-priority notifications trigger the heads-up notification display.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>DEFAULT</code></p> -</td> - <td class="tab1"> -<p>Use for all notifications that don't fall into any of the other priorities described here.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>LOW</code></p> -</td> - <td class="tab1"> -<p>Use for notifications that you want the user to be informed about, but -that are less urgent. Low-priority notifications tend to show up at the bottom of the list, -which makes them a good -choice for things like public or undirected social updates: The user has asked to -be notified about -them, but these notifications should never take precedence over urgent or direct -communication.</p> -</td> - </tr> - <tr> - <td class="tab1"> -<p><code>MIN</code></p> -</td> - <td class="tab1"> -<p>Use for contextual or background information such as weather information or contextual -location information. -Minimum-priority notifications do not appear in the status bar. The user -discovers them on expanding the notification shade.</p> -</td> - </tr> -</table> - - -<h4 id="how_to_choose_an_appropriate_priority"><strong>How to choose an -appropriate -priority</strong></h4> - -<p><code>DEFAULT</code>, <code>HIGH</code>, and <code>MAX</code> are interruptive priority levels, and risk -interrupting the user -in mid-activity. To avoid annoying your app's users, reserve interruptive priority levels for -notifications that:</p> - -<ul> - <li> Involve another person</li> - <li> Are time-sensitive</li> - <li> Might immediately change the user's behavior in the real world</li> -</ul> - -<p>Notifications set to <code>LOW</code> and <code>MIN</code> can still be -valuable for the user: Many, if not most, notifications just don't need to command the user's -immediate attention, or vibrate the user's wrist, yet contain information that the user will find -valuable when they choose to -look for notifications. Criteria for <code>LOW</code> and <code>MIN</code> -priority notifications include:</p> - -<ul> - <li> Don't involve other people</li> - <li> Aren't time sensitive</li> - <li> Contain content the user might be interested in but could choose to -browse at their leisure</li> -</ul> - - - <img -src="{@docRoot}images/android-5.0/notifications/notifications_pattern_priority.png" - alt="" width="700"/> - - -<h3 style="clear:both" id="set_a_notification_category">Set a notification -category</h3> - -<p>If your notification falls into one of the predefined categories (see -below), assign it -accordingly. Aspects of the system UI such as the notification shade (or any -other notification -listener) may use this information to make ranking and filtering decisions.</p> -<table> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_CALL">CATEGORY_CALL</a></code></p> -</td> - <td> -<p>Incoming call (voice or video) or similar synchronous communication -request</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_MESSAGE">CATEGORY_MESSAGE</a></code></p> -</td> - <td> -<p>Incoming direct message (SMS, instant message, etc.)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EMAIL">CATEGORY_EMAIL</a></code></p> -</td> - <td> -<p>Asynchronous bulk message (email)</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_EVENT">CATEGORY_EVENT</a></code></p> -</td> - <td> -<p>Calendar event</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROMO">CATEGORY_PROMO</a></code></p> -</td> - <td> -<p>Promotion or advertisement</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ALARM">CATEGORY_ALARM</a></code></p> -</td> - <td> -<p>Alarm or timer</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_PROGRESS">CATEGORY_PROGRESS</a></code></p> -</td> - <td> -<p>Progress of a long-running background operation</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SOCIAL">CATEGORY_SOCIAL</a></code></p> -</td> - <td> -<p>Social network or sharing update</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_ERROR">CATEGORY_ERROR</a></code></p> -</td> - <td> -<p>Error in background operation or authentication status</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_TRANSPORT">CATEGORY_TRANSPORT</a></code></p> -</td> - <td> -<p>Media transport control for playback</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SYSTEM">CATEGORY_SYSTEM</a></code></p> -</td> - <td> -<p>System or device status update. Reserved for system use.</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_SERVICE">CATEGORY_SERVICE</a></code></p> -</td> - <td> -<p>Indication of running background service</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_RECOMMENDATION">CATEGORY_RECOMMENDATION</a></code></p> -</td> - <td> -<p>A specific, timely recommendation for a single thing. For example, a news -app might want to -recommend a news story it believes the user will want to read next.</p> -</td> - </tr> - <tr> - <td> -<p><code><a -href="/reference/android/app/Notification.html#CATEGORY_STATUS">CATEGORY_STATUS</a></code></p> -</td> - <td> -<p>Ongoing information about device or contextual status</p> -</td> - </tr> -</table> - -<h3 id="summarize_your_notifications">Summarize your notifications</h3> - -<p>If a notification of a certain type is already pending when your app tries to send a new -notification of the same type, combine them into a single summary notification for the app. Do not -create a new object.</p> - -<p>A summary notification builds a summary description and allows the user to -understand how many -notifications of a particular kind are pending.</p> - -<div class="col-6"> - -<p><strong>Don't</strong></p> - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Dont.png" - alt="" width="311px" /> -</div> - -<div> -<p><strong>Do</strong></p> - - <img src="{@docRoot}images/android-5.0/notifications/Summarise_Do.png" - alt="" width="311px"/> -</div> - -<p style="clear:left; padding-top:30px; padding-bottom:20px">You can provide -more detail about the individual notifications that make up a - summary by using the expanded digest layout. This approach allows users to gain a -better sense of which - notifications are pending and if they are interesting enough to read in -detail within the - associated app.</p> -<div class="col-6"> - <img src="{@docRoot}images/android-5.0/notifications/Stack.png" -style="margin-bottom:20px" - alt="" width="311px" /> - <p class="img-caption"> - Expanded and contracted notification that is a summary (using <code>InboxStyle</code>) - </p> -</div> - -<h3 style="clear:both" id="make_notifications_optional">Make notifications -optional</h3> - -<p>Users should always be in control of notifications. Allow the user to -disable your app's -notifications or change their alert properties, such as alert sound and whether -to use vibration, -by adding a notification settings item to your application settings.</p> - -<h3 id="use_distinct_icons">Use distinct icons</h3> -<p>By glancing at the notification area, the user should be able to discern -what kinds of -notifications are currently pending.</p> - -<div class="figure"> - <img src="{@docRoot}images/android-5.0/notifications/ProductIcons.png" - alt="" width="420" /> -</div> - - <div><p><strong>Do</strong></p> - <p>Look at the notification icons Android apps already provide and create -notification icons for - your app that are sufficiently distinct in appearance.</p> - - <p><strong>Do</strong></p> - <p>Use the proper <a -href="/design/style/iconography.html#notification">notification icon style</a> - for small icons, and the Material Light - <a href="/design/style/iconography.html#action-bar">action bar icon -style</a> for your action - icons.</p> -<p ><strong>Do</strong></p> -<p >Keep your icons visually simple, avoiding excessive detail that is hard to -discern.</p> - - <div><p><strong>Don't</strong></p> - <p>Place any additional alpha (dimming or fading) into your -small icons and action - icons; they can have anti-aliased edges, but because Android uses these -icons as masks (that is, only - the alpha channel is used), the image should generally be drawn at full -opacity.</p> - -</div> -<p style="clear:both"><strong>Don't</strong></p> - -<p>Use color to distinguish your app from others. Notification icons should -only be a white-on-transparent background image.</p> - - -<h3 id="pulse_the_notification_led_appropriately">Pulse the notification LED -appropriately</h3> - -<p>Many Android devices contain a notification LED, which is used to keep the -user informed about -events while the screen is off. Notifications with a priority level of <code>MAX</code>, -<code>HIGH</code>, or <code>DEFAULT</code> should -cause the LED to glow, while those with lower priority (<code>LOW</code> and -<code>MIN</code>) should not.</p> - -<p>The user's control over notifications should extend to the LED. When you use -DEFAULT_LIGHTS, the -LED will glow white. Your notifications shouldn't use a different -color unless the -user has explicitly customized it.</p> - -<h2 id="building_notifications_that_users_care_about">Building Notifications -That Users Care About</h2> - -<p>To create an app that users love, it is important to design your -notifications carefully. -Notifications embody your app's voice, and contribute to your app's -personality. Unwanted or -unimportant notifications can annoy the user or make them resent how much -attention the app wants -from them, so use notifications judiciously.</p> - -<h3 id="when_to_display_a_notification">When to display a notification</h3> - -<p>To create an application that people enjoy using, it's important to -recognize that the user's -attention and focus is a resource that must be protected. While Android's -notification system has -been designed to minimize the impact of notifications on the user's attention, -it is -still important to be aware of the fact that notifications are interrupting the -user's task flow. -As you plan your notifications, ask yourself if they are important enough to -warrant an interruption. If you are unsure, allow the user to opt into a -notification using your apps notification settings, or adjust -the notifications priority flag to <code>LOW</code> or <code>MIN</code> to -avoid distracting the user while they are doing -something else.</p> - - <img src="{@docRoot}images/android-5.0/notifications/TimeSensitive.png" - alt="" width="311px" /> - <p style="margin-top:10px" class="img-caption"> - Examples of time-sensitive notification - </p> - -<p>While well-behaved apps generally only speak when spoken to, a few cases -do merit an app's interrupting the user with an unprompted notification.</p> - -<p>Use notifications primarily for <strong>time-sensitive events</strong>, especially - if these synchronous events <strong>involve other people</strong>. For -instance, an incoming chat - is a real-time and synchronous form of communication: Another user -actively waiting on your response. Calendar events are another good example of when to use a -notification and grab the - user's attention, because the event is imminent, and calendar events often -involve other people.</p> - -<h3 style="clear:both" id="when_not_to_display_a_notification">When not to -display a notification</h3> - -<div class="figure" style="margin-top:60px"> - <img src="{@docRoot}images/android-5.0/notifications/AntiSample1.png" - alt="" width="311px" /> -</div> - -<p>In many other cases, notifications aren't appropriate:</p> - -<ul> - <li> Avoid notifying the user of information that is not directed -specifically at them, or - information that is not truly time-sensitive. For instance, the asynchronous -and undirected updates - flowing through a social network generally do not warrant a real-time -interruption. For the users - who do care about them, allow them to opt-in.</li> - <li> Don't create a notification if the relevant new information is currently -on screen. Instead, - use the UI of the application itself to notify the user of new information -directly in context. - For instance, a chat application should not create system notifications while -the user is actively chatting with another user.</li> - <li> Don't interrupt the user for low-level technical operations, like saving -or syncing information, or updating an application if the app or system can resolve the issue -without involving the user.</li> - <li> Don't interrupt the user to inform them of an error if it is possible -for the application to recover from the error on its own without the user -taking any action.</li> - <li> Don't create notifications that have no true notification content and -merely advertise your - app. A notification should provide useful, timely, new information and should -not be used - merely to launch an app.</li> - <li> Don't create superfluous notifications just to get your brand in front -of users. - Such notifications frustrate and likely alienate your audience. The -best way to provide - small amounts of updated information and keep them engaged -with your - app is to develop a widget that they can choose to place on their -home screen.</li> -</ul> - -<h2 style="clear:left" id="interacting_with_notifications">Interacting with -Notifications</h2> - -<p>Notifications are indicated by icons in the status bar, and can be accessed -by opening the -notification drawer.</p> - -<p>Touching a notification opens the associated app to detailed content -that matches the notification. -Swiping left or right on a notification removes it from the drawer.</p> - -<h3 id="ongoing_notifications">Ongoing notifications</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/MusicPlayback.png" - alt="" width="311px" /> - <p class="img-caption"> - Ongoing notification due to music playback - </p> -</div> -<p>Ongoing notifications keep users informed about an ongoing process in the -background. -For example, music players announce the currently playing track in the -notification system and -continue to do so until the user stops the playback. Ongoing notifications can also -show the user -feedback for longer tasks like downloading a file, or encoding a video. A user cannot manually -remove an ongoing notification from the notification drawer.</p> - -<h3 id="ongoing_notifications">Media playback</h3> -<p>In Android 5.0, the lock screen doesn't show transport controls for the deprecated -{@link android.media.RemoteControlClient} class. But it <em>does</em> show notifications, so each -app's playback notification is now the primary -way for users to control playback from a locked state. This behavior gives apps more -control over which -buttons to show, and in what way, while providing a consistent experience for -the user whether or not the screen is locked.</p> - -<h3 style="clear:both" -id="dialogs_and_toasts_are_for_feedback_not_notification">Dialogs -and toasts</h3> - -<p>Your app should not create a dialog or toast if it is not currently on -screen. A dialog or toast - should only be displayed as an immediate response to the user taking an action -inside of your app. -For further guidance on the use of dialogs and toasts, refer to -<a href="/design/patterns/confirming-acknowledging.html">Confirming & Acknowledging</a>.</p> - -<h3>Ranking and ordering</h3> - -<p>Notifications are news, and so are essentially shown in -reverse-chronological order, with -special consideration given to the app's stated notification -<a href="#correctly_set_and_manage_notification_priority">priority</a>.</p> - -<p>Notifications are a key part of the lock screen, and are featured prominently -every -time the device display comes on. Space on the lock screen is tight, so it -is more important -than ever to identify the most urgent or relevant notifications. For this -reason, Android has a -more sophisticated sorting algorithm for notifications, taking into account:</p> - -<ul> - <li> The timestamp and application's stated priority.</li> - <li> Whether the notification has recently disturbed the user with sound or -vibration. (That is, - if the phone just made a noise, and the user wants to know "What just -happened?", the lock screen - should answer that at a glance.)</li> - <li> Any people attached to the notification using {@link android.app.Notification#EXTRA_PEOPLE}, - and, in particular, whether they are starred contacts.</li> -</ul> - -<p>To best take advantage of this sorting, focus on the user -experience you want -to create, rather than aiming for any particular spot on the list.</p> - - <img src="{@docRoot}images/android-5.0/notifications/AntiSample3.png" - alt="" width="700px" /> - - <p class="img-caption" style="margin-top:10px">Gmail notifications are -default priority, so they - normally sort below messages from an instant messaging app like Hangouts, but -get a - temporary bump when new messages come in. - </p> - - -<h3>On the lock screen</h3> - -<p>Because notifications are visible on the lock screen, user privacy is an -especially -important consideration. Notifications often contain sensitive information, and -should not necessarily be visible -to anyone who picks up the device and turns on the display.</p> - -<ul> - <li> For devices that have a secure lock screen (PIN, pattern, or password), the interface has - public and private parts. The public interface can be displayed on a secure lock screen and - therefore seen by anyone. The private interface is the world behind that lock screen, and - is only revealed once the user has signed into the device.</li> -</ul> - -<h3>User control over information displayed on the secure lock screen</h3> -<div class="figure" style="width:311px"> - <img src="{@docRoot}images/android-5.0/notifications/LockScreen@2x.png" - srcset="{@docRoot}images/android-5.0/notifications/LockScreen.png 1x" alt="" width="311px"/> - <p class="img-caption"> - Notifications on the lock screen, with contents revealed after the user unlocks the device. - </p> -</div> - -<p>When setting up a secure lock screen, the user can choose to conceal -sensitive details from the secure lock screen. In this case the System UI -considers the notification's <em>visibility level</em> to figure out what can -safely be shown.</p> -<p> To control the visibility level, call -<code><a -href="/reference/android/app/Notification.Builder.html#setVisibility(int)">Notification.Builder.setVisibility()</a></code>, -and specify one of these values:</p> - -<ul> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PUBLIC">VISIBILITY_PUBLIC</a></code>. -Shows the notification's full content. - This is the system default if visibility is left unspecified.</li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_PRIVATE">VISIBILITY_PRIVATE</a></code>. -On the lock screen, shows basic information about the existence of this notification, including its -icon and the name of the app that posted it. The rest of the notification's details are not displayed. -A couple of good points to keep in mind are as follows: - <ul> - <li> If you want to provide a different public version of your notification -for the system to display on a secure lock screen, supply a replacement -Notification object in the <code><a -href="/reference/android/app/Notification.html#publicVersion">Notification.publicVersion</a></code> -field. - <li> This setting gives your app an opportunity to create a redacted version of the -content that is still useful but does not reveal personal information. Consider the example of an -SMS app whose notifications include the text of the SMS and the sender's name and contact icon. -This notification should be <code>VISIBILITY_PRIVATE</code>, but <code>publicVersion</code> could still -contain useful information like "3 new messages" without any other identifying -details. - </ul> - </li> - <li><code><a -href="/reference/android/app/Notification.html#VISIBILITY_SECRET">Notification.VISIBILITY_SECRET</A></code>. Shows only the most minimal information, excluding -even the notification's icon.</li> -</ul> -<h2 style="clear:both" id="notifications_on_android_wear">Notifications on -Android Wear</h2> - -<p>Notifications and their <em>actions</em> are bridged over to Wear devices by default. -Developers can control which notifications bridge from the -phone to the watch, -and vice-versa. Developers can also control which actions bridge, as well. If -your app includes -actions that can't be accomplished with a single tap, either hide these actions -on your Wear -notification or consider hooking them up to a Wear app, thus allowing the user to -finish the action on -their watch.</p> - -<h4>Bridging notifications and actions</h4> - -<p>A connected device, such as a phone, can bridge notifications to a Wear device, so that the -notifications are displayed there. Similarly, it can bridge actions, so that the user can act -on the notifications right from the Wear device.</p> - -<p><strong>Bridge</strong></p> - -<ul> - <li> New instant messages</li> - <li> Single-tap actions such as +1, Like, Heart</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/WearBasic.png" width="156px" -height="156px" - alt="" /> - -<p><strong>Don't bridge</strong></p> - -<ul> - <li> Notifications of newly arrived podcasts</li> - <li> Actions that map to features that aren't possible on the watch</li> -</ul> - - - -<p><h4>Unique actions to define for Wear</h4></p> - -<p>There are some actions that you can perform only on Wear. These include the following:</p> - -<ul> - <li> Quick lists of canned responses such as "Be right back"</li> - <li> Open on the phone</li> - <li> A "Comment" or "Reply" action that brings up the speech input screen</li> - <li> Actions that launch Wear-specific apps</li> -</ul> - -<img src="{@docRoot}images/android-5.0/notifications/ReplyAction.png" width="156px" -height="156px" - alt="" /> diff --git a/docs/html/design/wear/style.jd b/docs/html/design/wear/style.jd index 75bd65f76317..804223fdf867 100644 --- a/docs/html/design/wear/style.jd +++ b/docs/html/design/wear/style.jd @@ -67,7 +67,7 @@ href="{@docRoot}design/wear/patterns.html#Continuing">Continuing activities on p <h2 id="KeepMinimum" style="clear:both">Keep Notifications to a Minimum</h2> -<p>Don’t abuse the user’s attention. Active notifications (that is, those that cause the device to vibrate) should only be used in cases that are both timely and involve a contact, for example receiving a message from a friend. Non-urgent notifications should be silently added to the Context Stream. See also the general <a href="{@docRoot}design/patterns/notifications.html">Android Notifications Guidelines</a>.</p> +<p>Don’t abuse the user’s attention. Active notifications (that is, those that cause the device to vibrate) should only be used in cases that are both timely and involve a contact, for example receiving a message from a friend. Non-urgent notifications should be silently added to the Context Stream. See also the general <a href="https://material.google.com/patterns/notifications.html">Android Notifications Guidelines</a>.</p> diff --git a/docs/html/distribute/engage/notifications.jd b/docs/html/distribute/engage/notifications.jd index c38f649a25a0..a37d703ccb62 100644 --- a/docs/html/distribute/engage/notifications.jd +++ b/docs/html/distribute/engage/notifications.jd @@ -10,7 +10,7 @@ page.image=/design/media/notifications_pattern_anatomy.png </div> <p> - The <a href="/design/patterns/notifications.html">notification system</a> + The <a href="https://material.google.com/patterns/notifications.html">notification system</a> allows your app to keep the user informed about events, such as new messages, upcoming calendar appointments, shared photos, and much more. They are a fundamental feature of Android that consumers check frequently to receive diff --git a/docs/html/distribute/essentials/optimizing-your-app.jd b/docs/html/distribute/essentials/optimizing-your-app.jd index 09c52d4ca2b9..d09a1a88d51a 100644 --- a/docs/html/distribute/essentials/optimizing-your-app.jd +++ b/docs/html/distribute/essentials/optimizing-your-app.jd @@ -475,7 +475,7 @@ who can help automate, measure, and optimize your mobile marketing. A great way to deliver a delightful user experience is to integrate tightly with the operating system. Features like <a href= "{@docRoot}guide/topics/appwidgets/index.html">Home screen widgets</a>, - <a href="{@docRoot}design/patterns/notifications.html">rich + <a href="https://material.google.com/patterns/notifications.html">rich notifications</a>, <a href="{@docRoot}guide/topics/search/index.html">global search integration</a>, and <a href= "{@docRoot}reference/android/widget/QuickContactBadge.html">Quick diff --git a/docs/html/distribute/essentials/quality/core.jd b/docs/html/distribute/essentials/quality/core.jd index 637eaac56ce4..3499f230fa05 100644 --- a/docs/html/distribute/essentials/quality/core.jd +++ b/docs/html/distribute/essentials/quality/core.jd @@ -186,7 +186,7 @@ page.image=/distribute/images/core-quality-guidelines.jpg <td> <p style="margin-bottom:.5em;"> Notifications follow Android Design <a href= - "{@docRoot}design/patterns/notifications.html">guidelines</a>. In + "https://material.google.com/patterns/notifications.html">guidelines</a>. In particular: </p> diff --git a/docs/html/distribute/essentials/quality/wear.jd b/docs/html/distribute/essentials/quality/wear.jd index fc1c73f65154..34c6cc566a90 100644 --- a/docs/html/distribute/essentials/quality/wear.jd +++ b/docs/html/distribute/essentials/quality/wear.jd @@ -18,7 +18,7 @@ page.image=/distribute/images/gp-wear-quality.png Core App Quality</a></li> <li><a href="{@docRoot}distribute/essentials/optimizing-your-app.html"> Optimize Your App</a></li> - <li><a href="{@docRoot}design/patterns/notifications.html"> + <li><a href="https://material.google.com/patterns/notifications.html"> Notifications</a></li> </ol> </div> diff --git a/docs/html/distribute/googleplay/developer-console.jd b/docs/html/distribute/googleplay/developer-console.jd index c826e82ca6f2..5a6c96fcb80e 100644 --- a/docs/html/distribute/googleplay/developer-console.jd +++ b/docs/html/distribute/googleplay/developer-console.jd @@ -10,30 +10,30 @@ Xnonavpage=true <div id="qv"> <h2>Features</h2> <ol> - <li><a href="#latest">Latest blog posts</a></li> - <li><a href="#publish">Publish with confidence</a></li> - <li><a href="#aquire-users">Acquire users</a></li> - <li><a href="#insights">Actionable insights</a></li> - <li><a href="#manage">Manage your app</a></li> + <li><a href="#latest">Latest Blog Posts</a></li> + <li><a href="#publish">Publish with Confidence</a></li> + <li><a href="#aquire-users">Acquire Users</a></li> + <li><a href="#insights">Learn about Users and App Performance</a></li> + <li><a href="#manage">Manage Your App</a></li> </ol> </div> </div> <p> - The <a href="https://play.google.com/apps/publish/">Google Play Developer - Console</a> is your home for publishing operations and tools. + The <a class="external-link" href="https://play.google.com/apps/publish/">Google Play Developer + Console</a> is your home for publishing and managing your apps. </p> <img src="{@docRoot}images/distribute/googleplay/gp-devconsole-home.png" style="width:480px;"> <p> - Upload apps, build your product pages, configure prices and distribution, and - publish. You can manage all phases of publishing on Google Play through the - Developer Console, from any web browser. + You can manage all phases of publishing on Google Play through the Developer + Console. Using any web browser, you can upload apps, build product pages, set + prices, configure distribution, and publish apps. </p> <p> - Once you've <a href= + After you've <a href= "{@docRoot}distribute/googleplay/start.html">registered</a> and received verification by email, you can sign in to your Google Play Developer Console. </p> @@ -44,7 +44,7 @@ Xnonavpage=true <div class="dynamic-grid"> <div class="headerLine"> -<h2 id="latest">Latest blog posts</h2> +<h2 id="latest">Latest Blog Posts</h2> </div> <div class="resource-widget resource-flow-layout col-13" @@ -54,103 +54,110 @@ Xnonavpage=true data-maxResults="3"></div> </div> -<h2 id="publish">Publish with confidence</h2> - +<h2 id="publish">Publish with Confidence</h2> +<p>The Developer Console provides rich testing features and staged rollouts that help you to + provide apps that satisfy your users.</p> <div class="wrap"> - <h3 id="alpha-beta">Alpha and beta tests</h3> + + <h3 id="cloud-test">Cloud Test Lab</h3> <div class="cols" style="margin-top:2em;"> <div class="col-3of12"> <p> - Distribute your pre-release app to users as an open beta with a - one-click, opt-in URL or as a closed beta using an email list, Google - Group, or Google+ community. Users can then provide feedback, while not - affecting your app’s public reviews and rating. This valuable feedback - will help you test features and improve the quality of your app. - <a href="{@docRoot}distribute/engage/beta.html">Learn more</a>. + Get free automated testing of your app on physical devices covering + nearly every brand, model, and version of the devices your users might + have. The lab helps you quickly find compatibility issues that you + might miss using only your available test devices. Sign up in the + Developer Console to become an early tester before this feature becomes + more widely available. <a href= + "https://developers.google.com/cloud-test-lab/" class= + "external-link">Learn more and sign up for updates.</a> </p> </div> <div class="col-8of12 col-push-1of12"> <img src= - "{@docRoot}images/distribute/googleplay/dev-console_running-a-beta-test.png" + "{@docRoot}images/distribute/googleplay/dev-console_cloud-test-lab.png" srcset= - "{@docRoot}images/distribute/googleplay/dev-console_running-a-beta-test.png 1x, {@docRoot}images/distribute/googleplay/dev-console_running-a-beta-test_2x.png 2x" + "{@docRoot}images/distribute/googleplay/dev-console_cloud-test-lab.png 1x, + {@docRoot}images/distribute/googleplay/dev-console_cloud-test-lab_2x.png 2x" width="500"> </div> </div> +</div> - <h3 id="cloud-test">Cloud Test Lab</h3> + <h3 id="alpha-beta">Alpha and beta tests</h3> <div class="cols" style="margin-top:2em;"> <div class="col-3of12"> <p> - Get free automated testing of your app on physical devices covering - nearly every brand, model, and version of the devices your users might - be using. The lab will help you quickly find compatibility issues you - may miss using only your available test devices. Sign-up in the - Developer Console to become an early tester before this feature becomes - more widely available. <a href= - "https://developers.google.com/cloud-test-lab/" class= - "external-link">Learn more and sign up for updates.</a> + Collect user feedback on early versions of your app with alpha and beta testing. + Distribute your pre-release app to users as an open beta with a + one-click, opt-in URL or as a closed beta using an email list, Google + Group, or Google+ community. Users can provide feedback, while not + affecting your app’s public reviews and rating. This valuable feedback + helps you test features and improve the quality of your app. + <a href="{@docRoot}distribute/engage/beta.html">Learn more</a>. </p> </div> <div class="col-8of12 col-push-1of12"> <img src= - "{@docRoot}images/distribute/googleplay/dev-console_cloud-test-lab.png" + "{@docRoot}images/distribute/googleplay/dev-console_running-a-beta-test.png" srcset= - "{@docRoot}images/distribute/googleplay/dev-console_cloud-test-lab.png 1x, {@docRoot}images/distribute/googleplay/dev-console_cloud-test-lab_2x.png 2x" + "{@docRoot}images/distribute/googleplay/dev-console_running-a-beta-test.png 1x, + {@docRoot}images/distribute/googleplay/dev-console_running-a-beta-test_2x.png 2x" width="500"> </div> </div> -</div> <h3 id="staged-rollouts">Staged rollouts</h3> <p> - Release app updates progressively to an increasing portion of your users and - monitor for missed issues. Then take the opportunity to fix problems before - all your users are affected. <a href= +Discover and fix problems with a limited user base before making a wider release. +With staged rollouts, you can release app updates progressively to an increasing portion of + your users. +You can fix problems before your app reaches the broader user community. <a href= "https://support.google.com/googleplay/android-developer/answer/3131213" - class="external-link">Learn more.</a> + class="external-link">Learn more</a>. </p> -<p class="aside"> - <strong>Tip:</strong> If you find an issue during a rollout stage you can - halt the rollout to further minimize the effect, and then resume rollout once - a fix has been made. +<p class="note"> + <strong>Tip:</strong> If you find an issue during a rollout stage, you can + halt the rollout, make the fix, and then resume. </p> -<h2 id="aquire-users">Aquire users</h2> - - <h3 id="adwords">AdWords Universal App Campaigns</h3> +<h2 id="aquire-users">Acquire Users</h2> +<p>Using the Developer Console, you can configure targeted ads to present your app to more users. + You can test variations of your Play Store listings and track user responses.</p> + <h3 id="adwords">Promote your app with AdWords</h3> <p> - Easily and conveniently buy AdWords app install ads, across Search + Easily and conveniently buy AdWords app install ads. AdWords Universal App Campaigns + appear across Search (including Play Search), YouTube, AdMob, and the Google Display Network. - Simply set a budget and cost per acquisition and Google takes care of the + Set a budget and cost per acquisition, and Google takes care of the rest. <a href="{@docRoot}distribute/users/promote-with-ads.html">Learn more</a>. </p> <div class="wrap"> - <h3 id="listing-experiments">Store Listing Experiments</h3> + <h3 id="listing-experiments">Increase installs with improved store listings</h3> <div class="cols" style="margin-top:2em;"> <div class="col-3of12"> - <p> - Test variations of the images and text used to promote and describe - your app on your Play store listing. Then when enough data has been - collected, choose to make the winning combination visible on Google + <p>With store listing experiments, + you can test variations of your app's Play Store listing. + You can try different combinations of images and text used to promote and describe + your app on its Play Store listing. Collect data, choose the best combination, and make + it visible on Google Play. <a href="{@docRoot}distribute/users/experiments.html">Learn more</a>. </p> - <p class="aside"> - <strong>Tip:</strong> You can even try out different orders for your - screenshots and other images to discover which grabs users’ attention - the best. + <p class="note"> + <strong>Tip:</strong> You can reorder your screenshots and other images in different ways + to determine the arrangement that best attracts users. </p> </div> @@ -158,20 +165,21 @@ Xnonavpage=true <img src= "{@docRoot}images/distribute/googleplay/dev-console_store-listing-experiment.png" srcset= - "{@docRoot}images/distribute/googleplay/dev-console_store-listing-experiment.png 1x, {@docRoot}images/distribute/googleplay/dev-console_store-listing-experiment_2x.png 2x" + "{@docRoot}images/distribute/googleplay/dev-console_store-listing-experiment.png 1x, + {@docRoot}images/distribute/googleplay/dev-console_store-listing-experiment_2x.png 2x" width="500"> </div> </div> - <h3 id="user-perf-report">User Acquisition performance report</h3> + <h3 id="user-perf-report">User acquisition performance report</h3> <div class="cols" style="margin-top:2em;"> <div class="col-3of12"> <p> - Discover where visitors to your Play Store listing come from, how many - go on to install your app, and how many buy your in-app products in the - User Acquisition performance report; compare cohorts, examine - acquisition channels, and see details of users and buyers. <a href= + Discover information about visitors to your Play Store listing, such as where they come + from, how many go on to install your app, and how many buy your in-app products. You + can also compare cohorts, examine acquisition channels, and see details of users and + buyers. <a href= "{@docRoot}distribute/users/user-acquisition.html">Learn more</a>. </p> </div> @@ -180,14 +188,16 @@ Xnonavpage=true <img src= "{@docRoot}images/distribute/googleplay/dev-console_conversion-funnel.png" srcset= - "{@docRoot}images/distribute/googleplay/dev-console_conversion-funnel.png 1x, {@docRoot}images/distribute/googleplay/dev-console_conversion-funnel_2x.png 2x" + "{@docRoot}images/distribute/googleplay/dev-console_conversion-funnel.png 1x, + {@docRoot}images/distribute/googleplay/dev-console_conversion-funnel_2x.png 2x" width="500"> </div> </div> </div> -<h2 id="insights">Actionable insights</h2> - +<h2 id="insights">Learn about App Users and Performance</h2> +<p>Using the Developer console, you can gain valuable insights about app performance. + You can better understand user behavior and find out ways to optimize your app. </p> <div class="wrap"> <h3 id="player-analytics">Player Analytics</h3> @@ -195,8 +205,10 @@ Xnonavpage=true <div class="cols" style="margin-top:2em;"> <div class="col-3of12"> <p> - With Google Play game services integration, discover more about the - behaviour of your game players; how they play and how they buy. Also get + Google Play game services offers a comprehensive dashboard of player and engagement + statistics. + With Player Analytics, discover more about the + behavior of your game users, including how they play and how they buy. Also get help setting and monitoring revenue budgets. <a href= "{@docRoot}distribute/engage/game-services.html">Learn more</a>. </p> @@ -206,7 +218,8 @@ Xnonavpage=true <img src= "{@docRoot}images/distribute/googleplay/dev-console_player-analytics.png" srcset= - "{@docRoot}images/distribute/googleplay/dev-console_player-analytics.png 1x, {@docRoot}images/distribute/googleplay/dev-console_player-analytics_2x.png 2x" + "{@docRoot}images/distribute/googleplay/dev-console_player-analytics.png 1x, + {@docRoot}images/distribute/googleplay/dev-console_player-analytics_2x.png 2x" width="500"> </div> </div> @@ -216,74 +229,77 @@ Xnonavpage=true <div class="cols" style="margin-top:2em;"> <div class="col-3of12"> <p> - Get a wide range of reports on the performance of your app and behaviour - of users; such as installs, revenue, crashes, and more. Turn on email - alerts to be notified of any sudden changes to important stats. <a href= - "https://support.google.com/googleplay/android-developer/topic/3450942?ref_topic=3450986" - class="external-link">Learn more.</a> + Get a wide range of reports on the performance of your app and behavior + of users such as installs, revenue, and crashes. Turn on email + alerts to receive notifications of any sudden changes to important stats. <a href= + "https://support.google.com/googleplay/android-developer/topic/3450942?ref_topic=3450986" + class="external-link">Learn more</a>. </p> </div> <div class="col-8of12 col-push-1of12"> <img src= "{@docRoot}images/distribute/googleplay/dev-console_statistics.png" srcset= - "{@docRoot}images/distribute/googleplay/dev-console_statistics.png 1x, {@docRoot}images/distribute/googleplay/dev-console_statistics_2x.png 2x" + "{@docRoot}images/distribute/googleplay/dev-console_statistics.png 1x, + {@docRoot}images/distribute/googleplay/dev-console_statistics_2x.png 2x" width="500"> </div> </div> </div> -<h3 id="optimization"> Optimization tips</h3> +<h3 id="optimization">Optimization tips</h3> <p> - Get tips, based on automatic app scanning, on ways in which you can improve - your app, everything from updating old APIs to suggestions for languages you - should consider localizing to. + Automatic app scanning provides tips on ways to improve your apps—everything + from updating old APIs to suggested languages for localization. </p> -<h2 id="manage">Manage your app</h2> +<h2 id="manage">Manage Your App</h2> <h3 id="manage-apks">Manage your APKs</h3> <p> Upload and manage your Android application packages (APK) to the Developer - Console as drafts or to your Alpha, Beta, or Production channels. <a href= + Console as drafts or to your Alpha, Beta, or Production channels. <a href= "https://support.google.com/googleplay/android-developer/answer/113469?ref_topic=3450986" - class="external-link">Learn more.</a> + class="external-link">Learn more</a>. </p> -<p class="aside"> - <strong>Tip:</strong> Ensure users get the best possible experience for the +<p class="note"> + <strong>Tip:</strong> Ensure that users get the best possible experience for the smallest app downloads by creating multiple APKs with just the right content - for device screen size, hardware features and more. + for hardware features such as screen size. For more information about using multiple APKs, + see <a href="https://developer.android.com/training/multiple-apks/index.html"> + Maintaining Multiple APKs.</a> </p> <h3 id="iap">In-app products and subscriptions</h3> <p> - Manage your in-app products and price them for local markets accordingly. - Offer weekly, monthly, annual, or seasonal subscriptions and take advantage - of features such as grace periods and trials. <a href= + Manage your in-app products and price them for local markets. + Offer weekly, monthly, annual, or seasonal subscriptions. Attract new users + with features such as grace periods and trials. <a href= "https://support.google.com/googleplay/android-developer/topic/3452896?ref_topic=3452890" - class="external-link">Learn more.</a> + class="external-link">Learn more</a>. </p> <h3 id="pricing">Pricing and distribution</h3> <p> - Control the price of your app for each country you choose to distribute to. - Make your app available to new audiences — opt-in to Android Auto, Android + Control the price of your app for each country that you distribute to. + Make your app available to new audiences—opt-in to Android Auto, Android TV, and Android Wear, as well as Designed for Families, Google Play for Work, and Google Play for Education. <a href= "https://support.google.com/googleplay/android-developer/answer/113469#pricing" class="external-link">Learn more</a>. </p> -<p class="external-link"> - <strong>Tip:</strong> You can set prices in other countries automatically - based on current exchange rates using the <strong>auto-convert prices - now</strong> feature. +<p class="note"> + <strong>Note:</strong> When you distribute your app to countries that use other currencies, + the Google Play Developer Console autofills country-specific prices based on current exchange + rates and locally-relevant pricing patterns. You can update the exchange rates manually by + selecting <strong>Refresh exchange rates</strong>. </p> <p style="clear:both"> diff --git a/docs/html/distribute/stories/apps/aftenposten.jd b/docs/html/distribute/stories/apps/aftenposten.jd index f1f388e2b6bd..a813c00addca 100644 --- a/docs/html/distribute/stories/apps/aftenposten.jd +++ b/docs/html/distribute/stories/apps/aftenposten.jd @@ -2,7 +2,7 @@ page.title=Aftenposten Improves Retention by Allowing Readers to Customize Notif page.metaDescription=Aftenposten upgraded their app and improved user retention. page.tags="developerstory", "apps", "googleplay" page.image=images/cards/distribute/stories/aftenposten.png -page.timestamp=1468270114 +page.timestamp=1468901834 @jd:body @@ -74,7 +74,7 @@ page.timestamp=1468270114 <p> Find out more about best practices for <a href= - "{@docRoot}design/patterns/notifications.html">Notifications</a> and <a href= + "https://material.google.com/patterns/notifications.html">Notifications</a> and <a href= "{@docRoot}training/building-content-sharing.html">Building Apps with Content Sharing</a>. </p> diff --git a/docs/html/distribute/stories/apps/el-mundo.jd b/docs/html/distribute/stories/apps/el-mundo.jd index 2ee813d55d11..2dbaeea7c8f0 100644 --- a/docs/html/distribute/stories/apps/el-mundo.jd +++ b/docs/html/distribute/stories/apps/el-mundo.jd @@ -2,7 +2,7 @@ page.title=El Mundo Improves User Ratings and Engagement with Material Design page.metaDescription=El Mundo uses Material Design principles to enhance their app's user experience. page.tags="developerstory", "apps", "googleplay" page.image=images/cards/distribute/stories/el-mundo.png -page.timestamp=1468270112 +page.timestamp=1468901833 @jd:body diff --git a/docs/html/distribute/stories/apps/segundamano.jd b/docs/html/distribute/stories/apps/segundamano.jd index 4cbf817c6d43..7ed4d8e88a5d 100644 --- a/docs/html/distribute/stories/apps/segundamano.jd +++ b/docs/html/distribute/stories/apps/segundamano.jd @@ -2,7 +2,7 @@ page.title=Segundamano Develops Android-First as Its Fastest Channel for Growth page.metaDescription=Segundamano developed Android app to increase potential for growth. page.tags="developerstory", "apps", "googleplay" page.image=images/cards/distribute/stories/segundamano.png -page.timestamp=1468270110 +page.timestamp=1468901832 @jd:body diff --git a/docs/html/distribute/stories/glu-dh.jd b/docs/html/distribute/stories/games/glu-dh.jd index 3353f6998ee1..3353f6998ee1 100644 --- a/docs/html/distribute/stories/glu-dh.jd +++ b/docs/html/distribute/stories/games/glu-dh.jd diff --git a/docs/html/distribute/stories/apps/tapps.jd b/docs/html/distribute/stories/games/tapps.jd index 129213946630..221b9a88622f 100644 --- a/docs/html/distribute/stories/apps/tapps.jd +++ b/docs/html/distribute/stories/games/tapps.jd @@ -1,8 +1,8 @@ page.title=Tapps Games Increases Installs by More Than 20% with Store Listing Experiments page.metaDescription=Tapps Games increased their use of store listing experiments in the Developer Console, with impressive results. -page.tags="developerstory", "apps", "googleplay" +page.tags="developerstory", "games", "googleplay" page.image=images/cards/distribute/stories/tapps.png -page.timestamp=1468270108 +page.timestamp=1468901831 @jd:body diff --git a/docs/html/distribute/stories/games/two-dots.jd b/docs/html/distribute/stories/games/two-dots.jd deleted file mode 100644 index a2299ce1f7f9..000000000000 --- a/docs/html/distribute/stories/games/two-dots.jd +++ /dev/null @@ -1,77 +0,0 @@ -page.title=Two Dots increased installs by 7 percent using Store Listing Experiments -page.metaDescription=Two Dots, the sequel to the popular game Dots, is a free-to-play puzzle game launched by Playdots, Inc. Playdots decided to use Store Listing Experiments to see if adding a call to action in the games’ store listing short descriptions had an impact on installs. -page.tags="developerstory", "games", "googleplay" -page.image=images/cards/distribute/stories/two-dots.png -page.timestamp=1456431511 - -@jd:body - - -<h3>Background</h3> - -<div class="figure" style="width:113px"> - <img src="{@docRoot}images/distribute/stories/two-dots-icon.png" - height="113" /> -</div> - -<p> - <a class="external-link" - href="https://play.google.com/store/apps/details?id=com.weplaydots.twodotsandroid&hl=en"> - Two Dots</a>, the sequel to the popular game - <a class="external-link" - href="https://play.google.com/store/apps/details?id=com.nerdyoctopus.gamedots&hl=en"> - Dots</a>, is a free-to-play puzzle game launched by Playdots, Inc. in May - 2014. Since launch it has gained over 30 million downloads, seen over five - billion games played, and achieved 15 times the revenue of the original Dots - game within a year. Dots decided to use - <a class="external-link" - href="https://support.google.com/googleplay/android-developer/answer/6227309"> - Store Listing Experiments</a> to see if adding a call to action in the games' - store listing short descriptions had an impact on installs. - -</p> - -<h3>What they did</h3> - -<p> - Dots used localized store listing experiments in the Google Play Developer - Console to test both games’ short descriptions. They compared the games’ - current descriptions — the control, with no call to action — against variant - descriptions, targeting half of their traffic with the variant descriptions. -</p> - -<h3>Results</h3> - -<p> - The results showed that the addition of a call to action in the short - description had a positive impact on installs. -</p> - - - <img - src="{@docRoot}images/distribute/stories/two-dots-screenshot.png" - srcset= - "{@docRoot}images/distribute/stories/two-dots-screenshot.png 1x - {@docRoot}images/distribute/stories/two-dots-screenshot_2x.png 2x"> - <p class="img-caption"> - Beautifully designed achievements badges encourage unlock - </p> - - -<p> - In Dots, the conversion rate increased by 2 percent with a simple call to - action in the variant text. In Two Dots, where a call to action was combined - with messaging that the game is the “best puzzle game on Android”, conversion - rates increased by 7 percent compared to the control description. -</p> - -<h3>Get started</h3> - -<p> - Learn how to run - <a clas="external-link" - href="https://support.google.com/googleplay/android-developer/answer/6227309"> - Store Listing Experiments</a> and read our best practices for - <a href="https://developer.android.com/distribute/users/experiments.html"> - running successful experiments</a>. -</p> diff --git a/docs/html/distribute/stories/apps/upbeat-games.jd b/docs/html/distribute/stories/games/upbeat-games.jd index 02222d39e686..16a1d51c19c9 100644 --- a/docs/html/distribute/stories/apps/upbeat-games.jd +++ b/docs/html/distribute/stories/games/upbeat-games.jd @@ -1,8 +1,8 @@ page.title=Witch Puzzle Achieves 98% of International Installs on Android page.metaDescription=Witch Puzzle localized their app into 12 languages. -page.tags="developerstory", "apps", "googleplay" +page.tags="developerstory", "games", "googleplay" page.image=images/cards/distribute/stories/witch-puzzle.png -page.timestamp=1468270106 +page.timestamp=1468901832 @jd:body diff --git a/docs/html/distribute/stories/index.jd b/docs/html/distribute/stories/index.jd index 8fe10191247d..1adc5aeb4eba 100644 --- a/docs/html/distribute/stories/index.jd +++ b/docs/html/distribute/stories/index.jd @@ -19,21 +19,43 @@ page.metaDescription=Android developers, their apps, and their successes with An <section class="dac-section dac-small" id="latest-apps"><div class="wrap"> <h2 class="norule">Latest from apps</h2> + <h3 class="norule">Videos</h3> + + <div class="resource-widget resource-flow-layout col-16" + data-query="type:youtube+tag:developerstory+tag:apps" + data-sortOrder="-timestamp" + data-cardSizes="6x6" + data-items-per-page="15" + data-initial-results="6"></div> + + <h3 class="norule">Articles</h3> + <div class="resource-widget resource-flow-layout col-16" - data-query="type:distribute+tag:developerstory+tag:apps, type:youtube+tag:developerstory+tag:apps" + data-query="type:distribute+tag:developerstory+tag:apps" data-sortOrder="-timestamp" data-cardSizes="6x6" data-items-per-page="15" - data-initial-results="9"></div> + data-initial-results="6"></div> </div></section> <section class="dac-section dac-small" id="latest-games"><div class="wrap"> <h2 class="norule">Latest from games</h2> + <h3 class="norule">Videos</h3> + + <div class="resource-widget resource-flow-layout col-16" + data-query="type:youtube+tag:developerstory+tag:games" + data-sortOrder="-timestamp" + data-cardSizes="6x6" + data-items-per-page="15" + data-initial-results="6"></div> + + <h3 class="norule">Articles</h3> + <div class="resource-widget resource-flow-layout col-16" - data-query="type:distribute+tag:developerstory+tag:games,type:youtube+tag:developerstory+tag:games" + data-query="type:distribute+tag:developerstory+tag:games" data-sortOrder="-timestamp" data-cardSizes="6x6" data-items-per-page="15" - data-initial-results="9"></div> + data-initial-results="6"></div> </div></section> diff --git a/docs/html/google/play/billing/billing_overview.jd b/docs/html/google/play/billing/billing_overview.jd index a05cc8d76992..7d932b7058ad 100644 --- a/docs/html/google/play/billing/billing_overview.jd +++ b/docs/html/google/play/billing/billing_overview.jd @@ -7,19 +7,20 @@ parent.link=index.html <div id="qv"> <h2>Quickview</h2> <ul> - <li>Use In-app Billing to sell digital goods, including one-time items and + <li>Use In-app Billing to sell digital products, including one-time products and recurring subscriptions.</li> - <li>Supported for any app published on Google Play. You only need a Google + <li>In-app Billing is supported for any app published on Google Play. You need only a + Google Play Developer Console account and a Google payments merchant account.</li> - <li>Checkout processing is automatically handled by Google Play, with the -same look-and-feel as for app purchases.</li> + <li>Google Play automatically handles checkout processing with the +same look and feel as app purchases.</li> </ul> <h2>In this document</h2> <ol> <li><a href="#api">In-app Billing API</a></li> <li><a href="#products">In-app Products</a> <ol> - <li><a href="#prodtypes">Product Types</a> + <li><a href="#prodtypes">Product types</a> </ol> </li> <li><a href="#console">Google Play Developer Console</a></li> @@ -27,30 +28,33 @@ same look-and-feel as for app purchases.</li> <li><a href="#samples">Sample App</a></li> <li><a href="#migration">Migration Considerations</a></li> </ol> - <h2>Related Samples</h2> + <h2>Related samples</h2> <ol> <li><a href="{@docRoot}training/in-app-billing/preparing-iab-app.html#GetSample">Sample Application (V3)</a></li> </ol> - <h2>Related Videos</h2> + <h2>Related videos</h2> <ol> - <li><a href="https://www.youtube.com/watch?v=UvCl5Xx7Z5o">Implementing + <li><a class="external-link" href="https://www.youtube.com/watch?v=UvCl5Xx7Z5o"> + Implementing Freemium</a></li> </ol> </div> </div> -<p>This documentation describes the fundamental In-app Billing components and +<p>This document describes the fundamental In-app Billing components and features that you need to understand in order to add In-app Billing features into your application.</p> -<p class="note"><b>Note</b>: Ensure that you comply with applicable laws in the countries where you -distribute apps. For example, in EU countries, laws based on the -<a href="http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=OJ:L:2005:149:0022:0039:EN:PDF"> -Unfair Commercial Practices Directive</a> prohibit direct exhortations to children to buy advertised -products or to persuade their parents or other adults to buy advertised products for them. -See the -<a href="http://ec.europa.eu/consumers/enforcement/docs/common_position_on_online_games_en.pdf"> +<p class="note"><b>Note</b>: Ensure that you comply with applicable laws in the countries where + you distribute apps. For example, in EU countries, laws based on the +<a class="external-link" + href="http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=OJ:L:2005:149:0022:0039:EN:PDF"> +Unfair Commercial Practices Directive</a> prohibit direct exhortations to children to buy + advertised products or to persuade their parents or other adults to buy advertised products + for them. See the +<a class="external-link" + href="http://ec.europa.eu/consumers/enforcement/docs/common_position_on_online_games_en.pdf"> position of the EU consumer protection authorities</a> for more information on this and other topics. </p> @@ -61,75 +65,82 @@ exposed by the Google Play app that is installed on the device. The Google Play app then conveys billing requests and responses between your application and the Google Play server. In practice, your application never directly communicates with the Google Play server. Instead, your application -sends billing requests to the Google Play application over interprocess +sends billing requests to the Google Play app over interprocess communication (IPC) and receives responses from the Google Play app. Your application does not manage any network connections between itself and the Google Play server.</p> -<p>In-app Billing can be implemented only in applications that you publish +<p>You can implement In-app Billing only in applications that you publish through Google Play. To complete in-app purchase requests, the Google Play app must be able to access the Google Play server over the network.</p> -<p>In-app billing Version 3 is the latest version, and maintains very broad +<p>In-app Billing Version 3 is the latest version, and it maintains very broad compatibility across the range of Android devices. In-app Billing Version 3 is -supported on devices running Android 2.2 or higher that have the latest version -of the Google Play store installed (<a +supported on devices running Android 2.2 (API level 8) or higher that have the latest version +of the Google Play app installed (<a href="{@docRoot}about/dashboards/index.html">a vast majority</a> of active devices).</p> <h4>Version 3 features</h4> +<p>In-app Billing Version 3 provides the following features:</p> <ul> -<li>Requests are sent through a streamlined API that allows you to easily request -product details from Google Play, order in-app products, and quickly restore -items based on users' product ownership</li> -<li>Order information is synchronously propagated to the device on purchase -completion</li> -<li>All purchases are “managed” (that is, Google Play keeps track of the user's -ownership of in-app products). The user cannot own multiple copies of an in-app -item; only one copy can be owned at any point in time</li> -<li>Purchased items can be consumed. When consumed, the item reverts to the -"unowned" state and can be purchased again from Google Play</li> -<li>Provides support for <a - href="{@docRoot}google/play/billing/billing_subscriptions.html">subscriptions</a></li> +<li>Your app sends requests through a streamlined API that allows users to easily request +product details from Google Play and order in-app products. The API quickly restores +products based on the user's ownership.</li> +<li>The API synchronously propagates order information to the device on purchase +completion.</li> +<li>All purchases are <em>managed</em> (that is, Google Play keeps track of the user's +ownership of in-app products). The user can't own multiple copies of an in-app +product; only one copy can be owned at any point in time.</li> +<li>Purchased products can be consumed. When consumed, the product reverts to the +<em>unowned</em> state and can be purchased again from Google Play.</li> +<li>The API provides support for <a + href="{@docRoot}google/play/billing/billing_subscriptions.html">subscriptions</a>.</li> </ul> <p>For details about other versions of In-app Billing, see the <a href="{@docRoot}google/play/billing/versions.html">Version Notes</a>.</p> <h2 id="products">In-app Products</h2> -<p>In-app products are the digital goods that you offer for sale from inside your -application to users. Examples of digital goods includes in-game currency, +<p>In-app products are the digital products that you offer for sale to users from inside your +application. Examples of digital products include in-game currency, application feature upgrades that enhance the user experience, and new content for your application.</p> <p>You can use In-app Billing to sell only digital content. -You cannot use In-app Billing to sell physical goods, personal services, or -anything that requires physical delivery. Unlike with priced applications, once -the user has purchased an in-app product there is no refund window.</p> +You can't use In-app Billing to sell physical products, personal services, or +anything that requires physical delivery. Unlike with priced applications, there is no refund + window after +the user has purchased an in-app product.</p> <p>Google Play does not provide any form of content delivery. You are responsible for delivering the digital content that you sell in your -applications. In-app products are always explicitly associated with one and -only one app. That is, one application cannot purchase an in-app product -published for another app, even if they are from the same developer.</p> +applications. In-app products are always explicitly associated with + only one app. That is, one application can't purchase an in-app product +that is published for another app, even if they are from the same developer.</p> <h3 id="prodtypes">Product types</h3> <p>In-app Billing supports different product types to give you flexibility in how you monetize your application. In all cases, you define your products using the Google Play Developer Console.</p> -<p>You can specify these types of products for your In-app Billing application -— <em>managed in-app products</em> and <em>subscriptions</em>. Google Play -handles and tracks ownership for in-app products and subscriptions on your -application on a per user account basis. -<a href="{@docRoot}google/play/billing/api.html#producttypes">Learn more about -the product types supported by In-app Billing Version 3</a>.</p> +<p>You can specify two product types for your In-app Billing application: + <em>managed in-app products</em> and <em>subscriptions</em>. Google Play +handles and tracks ownership for in-app products and subscriptions for your +application on a per-user basis. +<a href="{@docRoot}google/play/billing/api.html#producttypes">Learn more</a> about +the product types supported by In-app Billing Version 3.</p> <h2 id="console">Google Play Developer Console</h2> <p>The Developer Console is where you can publish your In-app Billing application and manage the various in-app products that are available for purchase from your application.</p> <p>You can create a product list of -digital goods that are associated with your application, including items for -one-time purchase and recurring subscriptions. For each item, you can define -information such as the item’s unique product ID (also called its SKU), product -type, pricing, description, and how Google Play should handle and track -purchases for that product.</p> +digital products that are associated with your application, including products for +one-time purchase and recurring subscriptions. You can define +information for each product such as the following:</p> +<ul> +<li>Unique product ID (also called its SKU).</li> +<li>Product type.</li> +<li>Pricing.</li> +<li>Description.</li> +<li>Google Play handling and tracking of purchases for that product.</li></p> +</ul> <p>If you sell several of your apps or in-app products at the same price, you can add <em>pricing templates</em> to manage these price points from a centralized location. When using pricing templates, you can include local taxes @@ -146,7 +157,7 @@ products and product list, see In-app Billing</a>.</p> <h2 id="checkout">Google Play Purchase Flow</h2> -<p>Google Play uses the same checkout backend service as is used for application +<p>Google Play uses the same backend checkout service that is used for application purchases, so your users experience a consistent and familiar purchase flow.</p> <p class="note"><strong>Important:</strong> You must have a Google payments merchant account to use the In-app Billing service on Google Play.</p> @@ -157,8 +168,8 @@ processing the financial transaction.</p> <p>When the checkout process is complete, Google Play sends your application the purchase details, such as the order number, the order date and time, and the price paid. At no point does your -application have to handle any financial transactions; that role is provided by -Google Play.</p> +application have to handle any financial transactions; that role belongs to + Google Play.</p> <h2 id="samples">Sample Application</h2> <p>To help you integrate In-app Billing into your application, the Android SDK @@ -166,16 +177,16 @@ provides a sample application that demonstrates how to sell in-app products and from inside an app.</p> <p>The <a href="{@docRoot}training/in-app-billing/preparing-iab-app.html#GetSample"> -TrivialDrive sample for the Version 3 API</a> sample shows how to use the In-app +TrivialDrive for the Version 3 API</a> sample shows how to use the In-app Billing Version 3 API to implement in-app product and subscription purchases for a driving game. The -application demonstrates how to send In-app Billing requests, and handle +application demonstrates how to send In-app Billing requests and handle synchronous responses from Google Play. The application also shows how to record -item consumption with the API. The Version 3 sample includes convenience classes +product consumption with the API. The Version 3 sample includes convenience classes for processing In-app Billing operations as well as perform automatic signature verification.</p> -<p class="caution"><strong>Recommendation</strong>: Make sure to obfuscate the +<p class="caution"><strong>Recommendation</strong>: Be sure to obfuscate the code in your application before you publish it. For more information, see <a href="{@docRoot}google/play/billing/billing_best_practices.html">Security and Design</a>.</p> @@ -183,16 +194,17 @@ and Design</a>.</p> <h2 id="migration">Migration Considerations</h2> <p>The In-app Billing Version 2 API was discontinued in January 2015. If you have an existing In-app Billing implementation that uses API Version 2 or -earlier, you must migrate to <a href="{@docRoot}google/play/billing/api.html">In-app Billing Version -3</a>.</p> +earlier, you must migrate to <a href="{@docRoot}google/play/billing/api.html"> +In-app Billing Version 3</a>.</p> -<p>If you have published apps selling in-app products, note that:</p> +<p>After migration, managed and unmanaged products are handled as follows:</p> <ul> -<li>Managed items and subscriptions that you have previously defined in the Developer Console will -work with Version 3 as before.</li> -<li>Unmanaged items that you have defined for existing applications will be -treated as managed products if you make a purchase request for these items using -the Version 3 API. You do not need to create a new product entry in Developer -Console for these items, and you can use the same product IDs to purchase these -items. +<li>Managed products and subscriptions that you have previously defined in the + Developer Console + work with Version 3 just as before.</li> +<li>Unmanaged products that you have defined for existing applications are + treated as managed products if you make a purchase request for these products using +the Version 3 API. You don't need to create a new product entry in the Developer +Console for these products, and you can use the same product IDs to manage these +products. </ul> diff --git a/docs/html/google/play/billing/billing_promotions.jd b/docs/html/google/play/billing/billing_promotions.jd index ccf50fc601c3..4fe1abfc4aa3 100644 --- a/docs/html/google/play/billing/billing_promotions.jd +++ b/docs/html/google/play/billing/billing_promotions.jd @@ -1,7 +1,7 @@ page.title=In-app Promotions parent.title=In-app Billing parent.link=index.html -page.metaDescription=Support promo codes in your app, which let you give content or features away to a limited number of users free of charge. +page.metaDescription=Support promo codes in your app, which lets you give content or features away to a limited number of users free of charge. page.image=/images/play_dev.jpg page.tags="promotions, billing, promo codes" meta.tags="monetization, inappbilling, promotions" @@ -13,7 +13,7 @@ meta.tags="monetization, inappbilling, promotions" <h2>In this document</h2> <ol> <li><a href="#workflow">Creating and Redeeming Promo Codes</a></li> - <li><a href="#supporting">Supporting Promo Codes In Your App</a></li> + <li><a href="#supporting">Supporting Promo Codes in Your App</a></li> <li><a href="#testing">Testing In-app Promotions</a></li> </ol> <h2>See also</h2> @@ -27,26 +27,26 @@ meta.tags="monetization, inappbilling, promotions" <p> Promo codes let you give content or features away to a limited number of - users free of charge. Once you create a promo code, you can distribute it + users free of charge. After you create a promo code, you can distribute it subject to the <!--TODO: Link to TOS when/if they're available as a web page --> terms of - service. The user enters the promo code in your app or in the Play Store app, - and gets the item at no cost. You can use promo codes in many ways to - creatively engage with users. For example: + service. The user enters the promo code in your app or in the Google Play Store app + and receives the item at no cost. You can use promo codes in many ways to + creatively engage with users, such as the following: </p> <ul> <li>A game could have a special item, such as a character or decoration, that's only available to players who attend an event. The developer could distribute cards with promo codes at the event, and users would enter their - promo code to unlock the item. + promo codes to unlock the item. </li> - <li>An app developer might distribute promo codes at local businesses, to + <li>An app developer might distribute promo codes at local businesses to encourage potential users to try the app. </li> - <li>An app developer might give out "friends and family" codes to its employees to + <li>An app developer might give <em>friends and family codes</em> to its employees to share with their friends. </li> </ul> @@ -54,11 +54,11 @@ meta.tags="monetization, inappbilling, promotions" <p> Every promo code is associated with a particular <em>product ID</em> (also known as a <em>SKU</em>). You can create promo codes for your existing in-app - products. You can also keep a SKU off the Play Store, so the only way to get + products. You can also keep an SKU off the Play Store, so that the only way to get that item is by entering that SKU's promo code. When a user enters the promo - code in the Play Store or in their app, the user gets the item, just as if + code in the Play Store or in an app, the user gets the item, just as if they paid full price for it. If your app already uses <a href= - "{@docRoot}google/play/billing/api.html">In-app Billing version 3</a> to + "{@docRoot}google/play/billing/api.html">In-app Billing Version 3</a> to support in-app purchases, it's easy to add support for promo codes. </p> @@ -67,12 +67,12 @@ meta.tags="monetization, inappbilling, promotions" <p> You create promo codes through the <a href= "https://play.google.com/apps/publish/" class="external-link">Google Play - Developer Console</a>. Each promo code is associated with a single product item + Developer Console</a>. Each promo code is associated with a single product registered in the developer console. </p> <p> - When a user gets a promo code, they redeem it in one of two ways: + A user can redeem a promo code in one of these two ways: </p> <ul> @@ -85,33 +85,20 @@ meta.tags="monetization, inappbilling, promotions" <li>The user can redeem the code in the Google Play Store app. Once the user enters the code, the Play Store prompts the user to open the app (if they have - the latest version installed) or to download or update it. (We do not - currently support redeeming promo codes from the Google Play web store.) + the latest version installed) or to download or update it. Google doesn't + currently support redeeming promo codes from the Google Play web store. </li> </ul> -<p> - If the promo code is for a <a href= - "{@docRoot}google/play/billing/api.html#consumetypes">consumable product</a>, - the user can apply an additional code for the same product <em>after</em> the first - product is consumed. For example, a game might offer promo codes for a bundle - of extra lives. Betty has two different promo codes for that bundle. She - redeems a single promo code, then launches the game. When the game launches, - the her character receives the lives, consuming the item. She can now redeem - the second promo code for another bundle of lives. (She cannot redeem the - second promo code until after she consumes the item she purchased with the - first promo code.) -</p> - -<h2 id="supporting">Supporting Promo Codes In Your App</h2> +<h2 id="supporting">Supporting Promo Codes in Your App</h2> <p> - To support promotion codes, your app should call the <a href= + To support promotion codes, your app must call the <a href= "{@docRoot}google/play/billing/billing_reference.html#getPurchases" ><code>getPurchases()</code></a> method whenever the app starts or resumes. This method returns a bundle of all current, unconsumed purchases, including purchases the user made by redeeming - a promo code. This simplest approach is to call <a href= + a promo code. The simplest approach is to call <a href= "{@docRoot}google/play/billing/billing_reference.html#getPurchases" ><code>getPurchases()</code></a> in your activity's {@link android.app.Activity#onResume onResume()} method, @@ -119,21 +106,21 @@ meta.tags="monetization, inappbilling, promotions" activity is unpaused. Calling <a href= "{@docRoot}google/play/billing/billing_reference.html#getPurchases" ><code>getPurchases()</code></a> - on startup and resume guarantees that your app will find out about all + on startup and resume guarantees that your app finds out about all purchases and redemptions the user may have made while the app wasn't running. Furthermore, if a user makes a purchase while the app is running and - your app misses it for any reason, your app will still find out about the + your app misses it for any reason, your app still finds out about the purchase the next time the activity resumes and calls <a href= "{@docRoot}google/play/billing/billing_reference.html#getPurchases" ><code>getPurchases()</code></a>. </p> <p> - In addition, your app should allow users to redeem promo codes inside the app + Your app should allow users to redeem promo codes inside the app itself. If your app supports the in-app purchase workflow (described in <a href= "{@docRoot}google/play/billing/billing_integrate.html#billing-requests">Making - In-app Billing Requests</a>), your app automatically supports in-app + In-app Billing requests</a>), your app automatically supports in-app redemption of promo codes. When you launch the in-app purchase UI, the user has the option to pay for the purchase with a promo code. Your activity's {@link android.app.Activity#onActivityResult @@ -141,9 +128,9 @@ meta.tags="monetization, inappbilling, promotions" purchase was completed. However, your app should still call <a href= "{@docRoot}google/play/billing/billing_reference.html#getPurchases" ><code>getPurchases()</code></a> - on startup and resume, just in case the purchase and consumption workflow - didn't complete. For example, if the user successfully redeems a promo code, - and then your app crashes before the item is consumed, your app still gets + on startup and resume, in case the purchase and consumption workflow + didn't complete. For example, if the user successfully redeems a promo code + and then your app crashes before the item is consumed, your app still receives information about the purchase when the app calls <a href= "{@docRoot}google/play/billing/billing_reference.html#getPurchases" ><code>getPurchases()</code></a> on its next startup. @@ -160,8 +147,8 @@ meta.tags="monetization, inappbilling, promotions" <p> To listen for the <code>PURCHASES_UPDATED</code> intent, dynamically create a {@link android.content.BroadcastReceiver} object and register it to listen - for <code>"com.android.vending.billing.PURCHASES_UPDATED"</code>. Register - the receiver by putting code like this in your activity's {@link + for <code>com.android.vending.billing.PURCHASES_UPDATED</code>. Register + the receiver by inserting code similar to the following in your activity's {@link android.app.Activity#onResume onResume()} method: </p> @@ -172,36 +159,34 @@ registerReceiver(myPromoReceiver, promoFilter);</pre> <p> When the user makes a purchase, the system invokes your broadcast receiver's {@link android.content.BroadcastReceiver#onReceive onReceive()} method. That - method should call <a href= + method must call <a href= "{@docRoot}google/play/billing/billing_reference.html#getPurchases" ><code>getPurchases()</code></a> to see what purchases the user has made. </p> -<p> - Your activity's {@link android.app.Activity#onPause onPause()} method should - unregister the broadcast receiver, to reduce system overhead when your app - isn't running: +<p>To reduce system overhead when your app + isn't running, your activity's {@link android.app.Activity#onPause onPause()} method must + unregister the broadcast receiver: </p> <pre>unRegisterReceiver(myPromoReceiver);</pre> <p class="note"> - <strong>Note:</strong> You should not register this broadcast receiver in the + <strong>Note:</strong> Don't register this broadcast receiver in the app manifest. Declaring the receiver in the manifest can cause the system to launch the app to handle the intent if the user makes a purchase while the app - isn't running. This behavior is not necessary, and may be annoying to the - user. Instead, your app should call <a href= - "{@docRoot}google/play/billing/billing_reference.html#getPurchases" - ><code>getPurchases()</code></a> - when the user launches it, to find out about any purchases the user made - while the app wasn't running. + isn't running. This behavior is not necessary and may be annoying to the + user. + To find out about any purchases the user made while the app wasn't running, + call <a href="{@docRoot}google/play/billing/billing_reference.html#getPurchases" + ><code>getPurchases()</code></a> when the user launches the app. </p> <h2 id="testing">Testing In-app Promotions</h2> <p> - If your app supports in-app promotions, you should test the following use + If your app supports in-app promotions, test the following use cases. </p> @@ -211,18 +196,18 @@ registerReceiver(myPromoReceiver, promoFilter);</pre> If the user redeems a promo code within the app's purchase flow, as described in <a href= "{@docRoot}google/play/billing/billing_integrate.html#billing-requests">Making - In-app Billing Requests</a>, the system invokes your activity's {@link + In-app Billing requests</a>, the system invokes your activity's {@link android.app.Activity#onActivityResult onActivityResult()} method to handle the purchase. Verify that {@link android.app.Activity#onActivityResult - onActivityResult()} handles the purchase properly, whether the user uses cash + onActivityResult()} handles the purchase properly, whether the user pays with money or a promo code. </p> -<h3 id="test-playstore">User redeems promo code in the Play Store</h3> +<h3 id="test-playstore">User redeems promo code in the Google Play Store</h3> <p> If the user redeems a promo code in the Play Store, there are several - possible workflows. You should verify each one of these. + possible workflows. Verify each one of these workflows. </p> <h4 id="test-app-uninstalled">App is not installed</h4> @@ -231,16 +216,16 @@ registerReceiver(myPromoReceiver, promoFilter);</pre> If the user redeems a promo code for an app that is not installed on the device, the Play Store prompts the user to install the app. (If the app is installed but not up-to-date, the Play Store prompts the user to update the - app.) You should test the following sequence on a device that does not + app.) Test the following sequence on a device that doesn't have your app installed. </p> <ol> - <li>User redeems a promo code for the app in the Play Store. The Play Store + <li>The user redeems a promo code for the app in the Play Store. The Play Store prompts the user to install your app. </li> - <li>User installs and launches your app. Verify that on startup, the app + <li>The user installs and launches your app. Verify that on startup, the app calls <a href= "{@docRoot}google/play/billing/billing_reference.html#getPurchases" ><code>getPurchases()</code></a> @@ -252,16 +237,16 @@ registerReceiver(myPromoReceiver, promoFilter);</pre> <p> If the user redeems a promo code for an app that is installed on the device, - the Play Store prompts the user to switch to the app. You should test the + the Play Store prompts the user to switch to the app. Test the following sequence on a device that has your app installed but not running: </p> <ol> - <li>User redeems a promo code for the app in the Play Store. The Play Store + <li>The user redeems a promo code for the app in the Play Store. The Play Store prompts the user to switch to your app. </li> - <li>User launches your app. Verify that on startup, the app calls <a href= + <li>The user launches your app. Verify that on startup the app calls <a href= "{@docRoot}google/play/billing/billing_reference.html#getPurchases" ><code>getPurchases()</code></a> and correctly detects the purchase the user made with the promo code. @@ -274,15 +259,15 @@ registerReceiver(myPromoReceiver, promoFilter);</pre> <p> If the user redeems a promo code for an app that is currently running on the device, the Play Store notifies the app via a <code>PURCHASES_UPDATED</code> - intent. You should test the following sequence: + intent. Test the following sequence: </p> <ol> - <li>User launches the app. Verify that the app has properly registered itself to + <li>The user launches the app. Verify that the app has properly registered itself to receive the <code>PURCHASES_UPDATED</code> intent. </li> - <li>User launches the Play Store app and redeems a promo code for the app. The Play + <li>The user launches the Play Store app and redeems a promo code for the app. The Play Store fires a <code>PURCHASES_UPDATED</code> intent. Verify that your app's {@link android.content.BroadcastReceiver#onReceive BroadcastReceiver.onReceive()} callback fires to handle the intent. @@ -291,11 +276,11 @@ registerReceiver(myPromoReceiver, promoFilter);</pre> <li>Your {@link android.content.BroadcastReceiver#onReceive onReceive()} method should respond to the intent by calling <a href= "{@docRoot}google/play/billing/billing_reference.html#getPurchases" - ><code>getPurchases()</code></a>. Verify that it calls this method, and that + ><code>getPurchases()</code></a>. Verify that your app calls this method and that it correctly detects the purchase the user made with the promo code. </li> - <li>User switches back to your app. Verify that the user has the purchased + <li>The user switches back to your app. Verify that the user has the purchased item. </li> </ol> diff --git a/docs/html/guide/topics/data/index.jd b/docs/html/guide/topics/data/index.jd index 169fc223d555..3872825f1619 100644 --- a/docs/html/guide/topics/data/index.jd +++ b/docs/html/guide/topics/data/index.jd @@ -11,13 +11,15 @@ page.landing.image= <div class="col-12"> <h3>Training</h3> - <a href="http://developer.android.com/training/cloudsync/index.html"> - <h4>Syncing to the Cloud</h4> - <p>This class covers different strategies for cloud enabled applications. It covers syncing -data with the cloud using your own back-end web application, and backing up data using the cloud so -that users can restore their data when installing your application on a new device.</p> + <a href="{@docRoot}training/backup/index.html"> + <h4>Backing up App Data to the Cloud</h4> + <p> + This class covers techniques for backing up data to the cloud so that + users can restore their data when recovering from a data loss (such as a + factory reset) or installing your application on a new device. + </p> </a> </div> -</div>
\ No newline at end of file +</div> diff --git a/docs/html/guide/topics/manifest/activity-element.jd b/docs/html/guide/topics/manifest/activity-element.jd index f30263e8983c..5ced295daa8a 100644 --- a/docs/html/guide/topics/manifest/activity-element.jd +++ b/docs/html/guide/topics/manifest/activity-element.jd @@ -25,7 +25,7 @@ parent.link=manifest-intro.html android:<a href="#hwaccel">hardwareAccelerated</a>=["true" | "false"] android:<a href="#icon">icon</a>="<i>drawable resource</i>" android:<a href="#label">label</a>="<i>string resource</i>" - android:<a href="#lmode">launchMode</a>=["multiple" | "singleTop" | + android:<a href="#lmode">launchMode</a>=["standard" | "singleTop" | "singleTask" | "singleInstance"] android:<a href="#maxRecents">maxRecents</a>="<i>integer</i>" android:<a href="#multi">multiprocess</a>=["true" | "false"] diff --git a/docs/html/guide/topics/manifest/manifest-intro.jd b/docs/html/guide/topics/manifest/manifest-intro.jd index c843567488e5..851674c0f780 100644 --- a/docs/html/guide/topics/manifest/manifest-intro.jd +++ b/docs/html/guide/topics/manifest/manifest-intro.jd @@ -6,50 +6,53 @@ page.title=App Manifest <h2>In this document</h2> <ol> -<li><a href="#filestruct">Structure of the Manifest File</a></li> -<li><a href="#filec">File Conventions</a> -<li><a href="#filef">File Features</a> - <ol> - <li><a href="#ifs">Intent Filters</a></li> - <li><a href="#iconlabel">Icons and Labels</a></li> - <li><a href="#perms">Permissions</a></li> - <li><a href="#libs">Libraries</a></li> - </ol></li> +<li><a href="#filestruct">Manifest file structure</a></li> +<li><a href="#filec">File conventions</a> +<li><a href="#filef">File features</a> + <ol> + <li><a href="#ifs">Intent filters</a></li> + <li><a href="#iconlabel">Icons and labels</a></li> + <li><a href="#perms">Permissions</a></li> + <li><a href="#libs">Libraries</a></li> + </ol></li> </ol> </div> </div> <p> - Every application must have an AndroidManifest.xml file (with precisely that + Every application must have an {@code AndroidManifest.xml} file (with precisely that name) in its root directory. <span itemprop="description">The manifest file - presents essential information about your app to the Android system, - information the system must have before it can run any of the app's - code.</span> Among other things, the manifest does the following: + provides essential information about your app to the Android system, which + the system must have before it can run any of the app's + code.</span> +</p> + +<p> +Among other things, the manifest file does the following: </p> <ul> <li>It names the Java package for the application. The package name serves as a unique identifier for the application.</li> -<li>It describes the components of the application — the activities, -services, broadcast receivers, and content providers that the application is -composed of. It names the classes that implement each of the components and -publishes their capabilities (for example, which {@link android.content.Intent -Intent} messages they can handle). These declarations let the Android system -know what the components are and under what conditions they can be launched.</li> +<li>It describes the components of the application, which include the activities, +services, broadcast receivers, and content providers that compose the application. +It also names the classes that implement each of the components and +publishes their capabilities, such as the {@link android.content.Intent +Intent} messages that they can handle. These declarations inform the Android system +of the components and the conditions in which they can be launched.</li> -<li>It determines which processes will host application components.</li> +<li>It determines the processes that host the application components.</li> -<li>It declares which permissions the application must have in order to -access protected parts of the API and interact with other applications.</li> - -<li>It also declares the permissions that others are required to have in +<li>It declares the permissions that the application must have in order to +access protected parts of the API and interact with other applications. It also declares +the permissions that others are required to have in order to interact with the application's components.</li> <li>It lists the {@link android.app.Instrumentation} classes that provide -profiling and other information as the application is running. These declarations +profiling and other information as the application runs. These declarations are present in the manifest only while the application is being developed and -tested; they're removed before the application is published.</li> +are removed before the application is published.</li> <li>It declares the minimum level of the Android API that the application requires.</li> @@ -57,16 +60,27 @@ requires.</li> <li>It lists the libraries that the application must be linked against.</li> </ul> +<p class="note"><strong>Note</strong>: As you prepare your Android app to run on Chromebooks, +there are some important hardware and software feature limitations that you should consider. See +the <a href="{@docRoot}topic/arc/manifest.html"> +App Manifest Compatibility for Chromebooks</a> document for more information. +</p> + +<h2 id="filestruct">Manifest file structure</h2> -<h2 id="filestruct">Structure of the Manifest File</h2> +<p> +The code snippet below shows the general structure of the manifest file and +every element that it can contain. Each element, along with all of its +attributes, is fully documented in a separate file. +</p> + +<p class="note"><strong>Tip</strong>: To view detailed +information about any of the elements that are mentioned within the text of this document, +simply click the element name. +</p> <p> -The diagram below shows the general structure of the manifest file and -every element that it can contain. Each element, along with all of its -attributes, is documented in full in a separate file. To view detailed -information about any element, click on the element name in the diagram, -in the alphabetical list of elements that follows the diagram, or on any -other mention of the element name. +Here is an example of the manifest file: </p> <pre> @@ -126,45 +140,45 @@ other mention of the element name. </pre> <p> -All the elements that can appear in the manifest file are listed below -in alphabetical order. These are the only legal elements; you cannot -add your own elements or attributes. +The following list contains all of the elements that can appear in the manifest file, +in alphabetical order: </p> -<p style="margin-left: 2em"> -<code><a href="{@docRoot}guide/topics/manifest/action-element.html"><action></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/activity-alias-element.html"><activity-alias></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/application-element.html"><application></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/category-element.html"><category></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/data-element.html"><data></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/grant-uri-permission-element.html"><grant-uri-permission></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/instrumentation-element.html"><instrumentation></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/intent-filter-element.html"><intent-filter></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/manifest-element.html"><manifest></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/meta-data-element.html"><meta-data></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/permission-element.html"><permission></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/permission-group-element.html"><permission-group></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/permission-tree-element.html"><permission-tree></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/provider-element.html"><provider></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/receiver-element.html"><receiver></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/service-element.html"><service></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/supports-screens-element.html"><supports-screens></a></code> <!-- ##api level 4## --> -<br/><code><a href="{@docRoot}guide/topics/manifest/uses-configuration-element.html"><uses-configuration></a></code> <!-- ##api level 3## --> -<br/><code><a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a></code> <!-- ##api level 4## --> -<br/><code><a href="{@docRoot}guide/topics/manifest/uses-library-element.html"><uses-library></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><uses-permission></a></code> -<br/><code><a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"><uses-sdk></a></code> -</p> - - +<ul> + <li><code><a href="{@docRoot}guide/topics/manifest/action-element.html"><action></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/activity-alias-element.html"><activity-alias></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/application-element.html"><application></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/category-element.html"><category></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/data-element.html"><data></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/grant-uri-permission-element.html"><grant-uri-permission></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/instrumentation-element.html"><instrumentation></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/intent-filter-element.html"><intent-filter></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/manifest-element.html"><manifest></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/meta-data-element.html"><meta-data></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/permission-element.html"><permission></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/permission-group-element.html"><permission-group></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/permission-tree-element.html"><permission-tree></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/provider-element.html"><provider></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/receiver-element.html"><receiver></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/service-element.html"><service></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/supports-screens-element.html"><supports-screens></a></code> <!-- ##api level 4## --></li> + <li><code><a href="{@docRoot}guide/topics/manifest/uses-configuration-element.html"><uses-configuration></a></code> <!-- ##api level 3## --></li> + <li><code><a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a></code> <!-- ##api level 4## --></li> + <li><code><a href="{@docRoot}guide/topics/manifest/uses-library-element.html"><uses-library></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><uses-permission></a></code></li> + <li><code><a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"><uses-sdk></a></code></li> +</ul> +<p class="note"><strong>Note</strong>: These are the only legal elements – you cannot +add your own elements or attributes. +</p> -<h2 id="filec">File Conventions</h2> +<h2 id="filec">File conventions</h2> <p> -Some conventions and rules apply generally to all elements and attributes -in the manifest: +This section describes the conventions and rules that apply generally to all of the elements and +attributes in the manifest file. </p> <dl> @@ -172,29 +186,28 @@ in the manifest: <dd>Only the <code><a href="{@docRoot}guide/topics/manifest/manifest-element.html"><manifest></a></code> and <code><a href="{@docRoot}guide/topics/manifest/application-element.html"><application></a></code> -elements are required, they each must be present and can occur only once. -Most of the others can occur many times or not at all — although at -least some of them must be present for the manifest to accomplish anything -meaningful. +elements are required. They each must be present and can occur only once. +Most of the other elements can occur many times or not at all. However, at +least some of them must be present before the manifest file becomes useful. <p> If an element contains anything at all, it contains other elements. -All values are set through attributes, not as character data within an element. +All of the values are set through attributes, not as character data within an element. </p> <p> -Elements at the same level are generally not ordered. For example, +Elements at the same level are generally not ordered. For example, the <code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code>, <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"><provider></a></code>, and <code><a href="{@docRoot}guide/topics/manifest/service-element.html"><service></a></code> elements can be intermixed in any sequence. There are two key exceptions to this -rule, however: +rule: <ul> <li> An <code><a href="{@docRoot}guide/topics/manifest/activity-alias-element.html"><activity-alias></a></code> element must follow the <code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code> - it is an alias for. + for which it is an alias. </li> <li> The <code><a href="{@docRoot}guide/topics/manifest/application-element.html"><application></a></code> @@ -207,15 +220,15 @@ rule, however: </p></dd> <dt><b>Attributes</b></dt> -<dd>In a formal sense, all attributes are optional. However, there are some -that must be specified for an element to accomplish its purpose. Use the -documentation as a guide. For truly optional attributes, it mentions a default +<dd>In a formal sense, all attributes are optional. However, there are some attributes +that must be specified so that an element can accomplish its purpose. Use the +documentation as a guide. For truly optional attributes, it mentions a default value or states what happens in the absence of a specification. <p>Except for some attributes of the root <code><a href="{@docRoot}guide/topics/manifest/manifest-element.html"><manifest></a></code> -element, all attribute names begin with an {@code android:} prefix — -for example, {@code android:alwaysRetainTaskState}. Because the prefix is +element, all attribute names begin with an {@code android:} prefix. +For example, {@code android:alwaysRetainTaskState}. Because the prefix is universal, the documentation generally omits it when referring to attributes by name.</p></dd> @@ -223,7 +236,7 @@ by name.</p></dd> <dd>Many elements correspond to Java objects, including elements for the application itself (the <code><a href="{@docRoot}guide/topics/manifest/application-element.html"><application></a></code> -element) and its principal components — activities +element) and its principal components: activities (<code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code>), services (<code><a href="{@docRoot}guide/topics/manifest/service-element.html"><service></a></code>), @@ -238,7 +251,7 @@ If you define a subclass, as you almost always would for the component classes {@link android.content.BroadcastReceiver}, and {@link android.content.ContentProvider}), the subclass is declared through a {@code name} attribute. The name must include the full package designation. -For example, an {@link android.app.Service} subclass might be declared as follows: +For example, a {@link android.app.Service} subclass might be declared as follows: </p> <pre><manifest . . . > @@ -251,12 +264,12 @@ For example, an {@link android.app.Service} subclass might be declared as follow </manifest></pre> <p> -However, as a shorthand, if the first character of the string is a period, the -string is appended to the application's package name (as specified by the +However, if the first character of the string is a period, the +application's package name (as specified by the <code><a href="{@docRoot}guide/topics/manifest/manifest-element.html"><manifest></a></code> element's <code><a href="{@docRoot}guide/topics/manifest/manifest-element.html#package">package</a></code> -attribute). The following assignment is the same as the one above: +attribute) is appended to the string. The following assignment is the same as that shown above: </p> <pre><manifest package="com.example.project" . . . > @@ -269,13 +282,13 @@ attribute). The following assignment is the same as the one above: </manifest></pre> <p> -When starting a component, Android creates an instance of the named subclass. +When starting a component, the Android system creates an instance of the named subclass. If a subclass isn't specified, it creates an instance of the base class. </p></dd> <dt><b>Multiple values</b></dt> <dd>If more than one value can be specified, the element is almost always -repeated, rather than listing multiple values within a single element. +repeated, rather than multiple values being listed within a single element. For example, an intent filter can list several actions: <pre><intent-filter . . . > @@ -286,108 +299,105 @@ For example, an intent filter can list several actions: </intent-filter></pre></dd> <dt><b>Resource values</b></dt> -<dd>Some attributes have values that can be displayed to users — for -example, a label and an icon for an activity. The values of these attributes -should be localized and therefore set from a resource or theme. Resource -values are expressed in the following format,</p> +<dd>Some attributes have values that can be displayed to users, such as +a label and an icon for an activity. The values of these attributes +should be localized and set from a resource or theme. Resource +values are expressed in the following format:</p> <p style="margin-left: 2em">{@code @[<i>package</i>:]<i>type</i>/<i>name</i>}</p> <p> -where the <i>package</i> name can be omitted if the resource is in the same package -as the application, <i>type</i> is a type of resource — such as "string" or -"drawable" — and <i>name</i> is the name that identifies the specific resource. -For example: +You can ommit the <i>package</i> name if the resource is in the same package +as the application. The <i>type</i> is a type of resource, such as <em>string</em> or +<em>drawable</em>, and the <i>name</i> is the name that identifies the specific resource. +Here is an example: </p> <pre><activity android:icon="@drawable/smallPic" . . . ></pre> <p> -Values from a theme are expressed in a similar manner, but with an initial '{@code ?}' -rather than '{@code @}': +The values from a theme are expressed similarly, but with an initial {@code ?} +instead of {@code @}: </p> <p style="margin-left: 2em">{@code ?[<i>package</i>:]<i>type</i>/<i>name</i>} </p></dd> <dt><b>String values</b></dt> -<dd>Where an attribute value is a string, double backslashes ('{@code \\}') -must be used to escape characters — for example, '{@code \\n}' for -a newline or '{@code \\uxxxx}' for a Unicode character.</dd> +<dd>Where an attribute value is a string, you must use double backslashes ({@code \\}) +to escape characters, such as {@code \\n} for +a newline or {@code \\uxxxx} for a Unicode character.</dd> </dl> - -<h2 id="filef">File Features</h2> +<h2 id="filef">File features</h2> <p> -The following sections describe how some Android features are reflected +The following sections describe the way that some Android features are reflected in the manifest file. </p> -<h3 id="ifs">Intent Filters</h3> +<h3 id="ifs">Intent filters</h3> <p> -The core components of an application (its activities, services, and broadcast -receivers) are activated by <i>intents</i>. An intent is a +The core components of an application, such as its activities, services, and broadcast +receivers, are activated by <i>intents</i>. An intent is a bundle of information (an {@link android.content.Intent} object) describing a -desired action — including the data to be acted upon, the category of +desired action, including the data to be acted upon, the category of component that should perform the action, and other pertinent instructions. -Android locates an appropriate component to respond to the intent, launches +The Android system locates an appropriate component that can respond to the intent, launches a new instance of the component if one is needed, and passes it the -Intent object. +{@link android.content.Intent} object. </p> <p> -Components advertise their capabilities — the kinds of intents they can -respond to — through <i>intent filters</i>. Since the Android system -must learn which intents a component can handle before it launches the component, +The components advertise the types of intents that they can +respond to through <i>intent filters</i>. Since the Android system +must learn the intents that a component can handle before it launches the component, intent filters are specified in the manifest as <code><a href="{@docRoot}guide/topics/manifest/intent-filter-element.html"><intent-filter></a></code> -elements. A component may have any number of filters, each one describing +elements. A component can have any number of filters, each one describing a different capability. </p> <p> -An intent that explicitly names a target component will activate that component; -the filter doesn't play a role. But an intent that doesn't specify a target by +An intent that explicitly names a target component activates that component, so +the filter doesn't play a role. An intent that doesn't specify a target by name can activate a component only if it can pass through one of the component's filters. </p> <p> -For information on how Intent objects are tested against intent filters, -see a separate document, -<a href="{@docRoot}guide/components/intents-filters.html">Intents -and Intent Filters</a>. +For information about how {@link android.content.Intent} objects are tested against intent filters, +see the <a href="{@docRoot}guide/components/intents-filters.html">Intents +and Intent Filters</a> document. </p> - -<h3 id="iconlabel">Icons and Labels</h3> +<h3 id="iconlabel">Icons and labels</h3> <p> A number of elements have {@code icon} and {@code label} attributes for a -small icon and a text label that can be displayed to users. Some also have a -{@code description} attribute for longer explanatory text that can also be -shown on-screen. For example, the +small icon and a text label that can be displayed to users. Some also have a +{@code description} attribute for longer, explanatory text that can also be +shown on-screen. For example, the <code><a href="{@docRoot}guide/topics/manifest/permission-element.html"><permission></a></code> -element has all three of these attributes, so that when the user is asked whether +element has all three of these attributes so that when the user is asked whether to grant the permission to an application that has requested it, an icon representing the permission, the name of the permission, and a description of what it -entails can all be presented to the user. +entails are all presented to the user. </p> <p> -In every case, the icon and label set in a containing element become the default +In every case, the icon and label that are set in a containing element become the default {@code icon} and {@code label} settings for all of the container's subelements. -Thus, the icon and label set in the +Thus, the icon and label that are set in the <code><a href="{@docRoot}guide/topics/manifest/application-element.html"><application></a></code> element are the default icon and label for each of the application's components. -Similarly, the icon and label set for a component — for example, an +Similarly, the icon and label that are set for a component, such as an <code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code> -element — are the default settings for each of the component's +element, are the default settings for each of the component's <code><a href="{@docRoot}guide/topics/manifest/intent-filter-element.html"><intent-filter></a></code> -elements. If an +elements. If an <code><a href="{@docRoot}guide/topics/manifest/application-element.html"><application></a></code> element sets a label, but an activity and its intent filter do not, the application label is treated as the label for both the activity and @@ -395,62 +405,62 @@ the intent filter. </p> <p> -The icon and label set for an intent filter are used to represent a component -whenever the component is presented to the user as fulfilling the function -advertised by the filter. For example, a filter with -"{@code android.intent.action.MAIN}" and -"{@code android.intent.category.LAUNCHER}" settings advertises an activity -as one that initiates an application — that is, as -one that should be displayed in the application launcher. The icon and label -set in the filter are therefore the ones displayed in the launcher. +The icon and label that are set for an intent filter represent a component +whenever the component is presented to the user and fulfills the function +that is advertised by the filter. For example, a filter with +{@code android.intent.action.MAIN} and +{@code android.intent.category.LAUNCHER} settings advertises an activity +as one that initiates an application. That is, as +one that should be displayed in the application launcher. The icon and label +that are set in the filter are displayed in the launcher. </p> - <h3 id="perms">Permissions</h3> <p> -A <i>permission</i> is a restriction limiting access to a part of the code -or to data on the device. The limitation is imposed to protect critical +A <i>permission</i> is a restriction that limits access to a part of the code +or to data on the device. The limitation is imposed to protect critical data and code that could be misused to distort or damage the user experience. </p> <p> -Each permission is identified by a unique label. Often the label indicates -the action that's restricted. For example, here are some permissions defined +Each permission is identified by a unique label. Often the label indicates +the action that's restricted. Here are some permissions that are defined by Android: </p> -<p style="margin-left: 2em">{@code android.permission.CALL_EMERGENCY_NUMBERS} -<br/>{@code android.permission.READ_OWNER_DATA} -<br/>{@code android.permission.SET_WALLPAPER} -<br/>{@code android.permission.DEVICE_POWER}</p> +<ul> + <li>{@code android.permission.CALL_EMERGENCY_NUMBERS}</li> + <li>{@code android.permission.READ_OWNER_DATA}</li> + <li>{@code android.permission.SET_WALLPAPER}</li> + <li>{@code android.permission.DEVICE_POWER}</li> +</ul> <p> -A feature can be protected by at most one permission. +A feature can be protected by only one permission. </p> <p> -If an application needs access to a feature protected by a permission, -it must declare that it requires that permission with a +If an application needs access to a feature that is protected by a permission, +it must declare that it requires the permission with a <code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><uses-permission></a></code> -element in the manifest. Then, when the application is installed on -the device, the installer determines whether or not to grant the requested +element in the manifest. When the application is installed on +the device, the installer determines whether to grant the requested permission by checking the authorities that signed the application's certificates and, in some cases, asking the user. If the permission is granted, the application is able to use the protected -features. If not, its attempts to access those features will simply fail +features. If not, its attempts to access those features fail without any notification to the user. </p> <p> -An application can also protect its own components (activities, services, -broadcast receivers, and content providers) with permissions. It can employ -any of the permissions defined by Android (listed in -{@link android.Manifest.permission android.Manifest.permission}) or declared -by other applications. Or it can define its own. A new permission is declared +An application can also protect its own components with permissions. It can employ +any of the permissions that are defined by Android, as listed in +{@link android.Manifest.permission android.Manifest.permission}, or declared +by other applications. It can also define its own. A new permission is declared with the <code><a href="{@docRoot}guide/topics/manifest/permission-element.html"><permission></a></code> -element. For example, an activity could be protected as follows: +element. For example, an activity could be protected as follows: </p> <pre> @@ -474,34 +484,34 @@ declared with the <code><a href="{@docRoot}guide/topics/manifest/permission-element.html"><permission></a></code> element, its use is also requested with the <code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><uses-permission></a></code> -element. Its use must be requested in order for other components of the +element. You must request its use in order for other components of the application to launch the protected activity, even though the protection is imposed by the application itself. </p> <p> -If, in the same example, the {@code permission} attribute was set to a -permission declared elsewhere -(such as {@code android.permission.CALL_EMERGENCY_NUMBERS}, it would not -have been necessary to declare it again with a +If, in the same example shown above, the {@code permission} attribute was set to a +permission that is declared elsewhere, +such as {@code android.permission.CALL_EMERGENCY_NUMBERS}, it would not +be necessary to declare it again with a <code><a href="{@docRoot}guide/topics/manifest/permission-element.html"><permission></a></code> -element. However, it would still have been necessary to request its use with +element. However, it would still be necessary to request its use with <code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><uses-permission></a></code>. </p> <p> The <code><a href="{@docRoot}guide/topics/manifest/permission-tree-element.html"><permission-tree></a></code> -element declares a namespace for a group of permissions that will be defined in -code. And +element declares a namespace for a group of permissions that are defined in +code, and the <code><a href="{@docRoot}guide/topics/manifest/permission-group-element.html"><permission-group></a></code> -defines a label for a set of permissions (both those declared in the manifest with +defines a label for a set of permissions, both those declared in the manifest with <code><a href="{@docRoot}guide/topics/manifest/permission-element.html"><permission></a></code> -elements and those declared elsewhere). It affects only how the permissions are -grouped when presented to the user. The +elements and those declared elsewhere. This affects only how the permissions are +grouped when presented to the user. The <code><a href="{@docRoot}guide/topics/manifest/permission-group-element.html"><permission-group></a></code> -element does not specify which permissions belong to the group; -it just gives the group a name. A permission is placed in the group +element does not specify the permissions that belong to the group, but +it gives the group a name. You can place a permission in the group by assigning the group name to the <code><a href="{@docRoot}guide/topics/manifest/permission-element.html"><permission></a></code> element's @@ -515,15 +525,14 @@ attribute. <p> Every application is linked against the default Android library, which includes the basic packages for building applications (with common classes -such as Activity, Service, Intent, View, Button, Application, ContentProvider, -and so on). +such as Activity, Service, Intent, View, Button, Application, and ContentProvider). </p> <p> -However, some packages reside in their own libraries. If your application -uses code from any of these packages, it must explicitly asked to be linked -against them. The manifest must contain a separate +However, some packages reside in their own libraries. If your application +uses code from any of these packages, it must explicitly ask to be linked +against them. The manifest must contain a separate <code><a href="{@docRoot}guide/topics/manifest/uses-library-element.html"><uses-library></a></code> -element to name each of the libraries. (The library name can be found in the -documentation for the package.) +element to name each of the libraries. You can find the library name in the +documentation for the package. </p> diff --git a/docs/html/guide/topics/media/camera.jd b/docs/html/guide/topics/media/camera.jd index 8b79b237fcee..c806c886a3cc 100644 --- a/docs/html/guide/topics/media/camera.jd +++ b/docs/html/guide/topics/media/camera.jd @@ -1243,7 +1243,7 @@ support and to what level. After making that decision, you should plan on includ camera application that checks to see if device hardware supports those features and fails gracefully if a feature is not available.</p> -<p>You can check the availabilty of camera features by getting an instance of a camera’s parameters +<p>You can check the availabilty of camera features by getting an instance of a camera's parameters object, and checking the relevant methods. The following code sample shows you how to obtain a {@link android.hardware.Camera.Parameters} object and check if the camera supports the autofocus feature:</p> @@ -1290,7 +1290,7 @@ mCamera.setParameters(params); <p>This technique works for nearly all camera features, and most parameters can be changed at any time after you have obtained an instance of the {@link android.hardware.Camera} object. Changes to -parameters are typically visible to the user immediately in the application’s camera preview. +parameters are typically visible to the user immediately in the application's camera preview. On the software side, parameter changes may take several frames to actually take effect as the camera hardware processes the new instructions and then sends updated image data.</p> @@ -1341,7 +1341,7 @@ mCamera.setParameters(params); </pre> <p>The {@link android.hardware.Camera.Area} object contains two data parameters: A {@link -android.graphics.Rect} object for specifying an area within the camera’s field of view and a weight +android.graphics.Rect} object for specifying an area within the camera's field of view and a weight value, which tells the camera what level of importance this area should be given in light metering or focus calculations.</p> @@ -1405,7 +1405,7 @@ class MyFaceDetectionListener implements Camera.FaceDetectionListener { } </pre> -<p>After creating this class, you then set it into your application’s +<p>After creating this class, you then set it into your application's {@link android.hardware.Camera} object, as shown in the example code below:</p> <pre> @@ -1480,7 +1480,7 @@ public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { <p class="note"><strong>Note:</strong> Remember to call this method <em>after</em> calling {@link android.hardware.Camera#startPreview startPreview()}. Do not attempt to start face detection -in the {@link android.app.Activity#onCreate onCreate()} method of your camera app’s main activity, +in the {@link android.app.Activity#onCreate onCreate()} method of your camera app's main activity, as the preview is not available by this point in your application's the execution.</p> diff --git a/docs/html/guide/topics/resources/complex-xml-resources.jd b/docs/html/guide/topics/resources/complex-xml-resources.jd index 66dcb58347ab..ebf7bc3f0228 100644 --- a/docs/html/guide/topics/resources/complex-xml-resources.jd +++ b/docs/html/guide/topics/resources/complex-xml-resources.jd @@ -93,8 +93,7 @@ Since we’re making an animated vector drawable, we put the file under <code>re </vector> <strong><aapt:attr /></strong> - <target - android:name="rotationGroup" /> + <target android:name="rotationGroup"> <strong><aapt:attr name="android:animation" ></strong> <objectAnimator android:duration="6000" @@ -102,6 +101,7 @@ Since we’re making an animated vector drawable, we put the file under <code>re android:valueFrom="0"
android:valueTo="360" /> <strong><aapt:attr></strong> + </target> </animated-vector> </pre> </dd> diff --git a/docs/html/guide/topics/ui/accessibility/apps.jd b/docs/html/guide/topics/ui/accessibility/apps.jd index 26fb3cca9dc3..ab8c792cd24b 100644 --- a/docs/html/guide/topics/ui/accessibility/apps.jd +++ b/docs/html/guide/topics/ui/accessibility/apps.jd @@ -160,7 +160,7 @@ focus navigation</a>.</p> {@code android:focusable}</a> attribute is set to {@code true}. This setting allows users to focus on the element using the directional controls and then interact with it. The user interface controls provided by the Android framework are focusable by default and visually indicate focus by changing -the control’s appearance.</p> +the control's appearance.</p> <p>Android provides several APIs that let you control whether a user interface control is focusable and even request that a control be given focus:</p> @@ -436,7 +436,7 @@ public boolean onKeyUp (int keyCode, KeyEvent event) { <h3 id="populate-events">Populating accessibility events</h3> <p>Each {@link android.view.accessibility.AccessibilityEvent} has a set of required properties that -describe the current state of the view. These properties include things such as the view’s class +describe the current state of the view. These properties include things such as the view's class name, content description and checked state. The specific properties required for each event type are described in the {@link android.view.accessibility.AccessibilityEvent} reference documentation. The {@link android.view.View} implementation provides default values for these properties. Many of diff --git a/docs/html/guide/topics/ui/accessibility/services.jd b/docs/html/guide/topics/ui/accessibility/services.jd index f91a9791a469..c6db855adba4 100644 --- a/docs/html/guide/topics/ui/accessibility/services.jd +++ b/docs/html/guide/topics/ui/accessibility/services.jd @@ -124,7 +124,7 @@ your accessibility service, as shown in the following example:</p> </service> </pre> -<p>This meta-data element refers to an XML file that you create in your application’s resource +<p>This meta-data element refers to an XML file that you create in your application's resource directory ({@code <project_dir>/res/xml/accessibility_service_config.xml}). The following code shows example contents for the service configuration file:</p> @@ -267,7 +267,7 @@ this way, the Android system can provide much richer detail about accessibility accessibility services to provide more useful feedback to users.</p> <p>An accessibility service gets information about an user interface event through an {@link -android.view.accessibility.AccessibilityEvent} passed by the system to the service’s +android.view.accessibility.AccessibilityEvent} passed by the system to the service's {@link android.accessibilityservice.AccessibilityService#onAccessibilityEvent onAccessibilityEvent()} callback method. This object provides details about the event, including the type of object being acted upon, its descriptive text and other details. Starting in Android 4.0 @@ -335,7 +335,7 @@ user actions). If your service requires all views, it can request them by settin of a user. This feature, added in Android 4.1 (API Level 16), and requires that your accessibility service request activation of the Explore by Touch feature. Your service can request this activation by setting the - {@link android.accessibilityservice.AccessibilityServiceInfo#flags flags} member of the service’s + {@link android.accessibilityservice.AccessibilityServiceInfo#flags flags} member of the service's {@link android.accessibilityservice.AccessibilityServiceInfo} instance to {@link android.accessibilityservice.AccessibilityServiceInfo#FLAG_REQUEST_TOUCH_EXPLORATION_MODE}, as shown in the following example. diff --git a/docs/html/guide/topics/ui/index.jd b/docs/html/guide/topics/ui/index.jd index ccdf200ecac6..7dbc01579ad3 100644 --- a/docs/html/guide/topics/ui/index.jd +++ b/docs/html/guide/topics/ui/index.jd @@ -13,7 +13,7 @@ page.landing.next=overview.html <a href="http://android-developers.blogspot.com/2012/01/say-goodbye-to-menu-button.html"> <h4>Say Goodbye to the Menu Button</h4> - <p>As Ice Cream Sandwich rolls out to more devices, it’s important that you begin to migrate + <p>As Ice Cream Sandwich rolls out to more devices, it's important that you begin to migrate your designs to the action bar in order to promote a consistent Android user experience.</p> </a> <a href="http://android-developers.blogspot.com/2011/11/new-layout-widgets-space-and-gridlayout.html"> @@ -29,7 +29,7 @@ way to interact with your application.</p> </a> <a href="http://android-developers.blogspot.com/2011/08/horizontal-view-swiping-with-viewpager.html"> <h4>Horizontal View Swiping with ViewPager</h4> <p>Whether you have just started out in Android app development or are a veteran of the craft, -it probably won’t be too long before you’ll need to implement horizontally scrolling sets of views. +it probably won't be too long before you'll need to implement horizontally scrolling sets of views. </p> </a> </div> diff --git a/docs/html/guide/topics/ui/notifiers/notifications.jd b/docs/html/guide/topics/ui/notifiers/notifications.jd index 6cd63f384a42..7212f93c3726 100644 --- a/docs/html/guide/topics/ui/notifiers/notifications.jd +++ b/docs/html/guide/topics/ui/notifiers/notifications.jd @@ -60,7 +60,7 @@ page.title=Notifications <h2>See also</h2> <ol> <li> - <a href="{@docRoot}design/patterns/notifications.html">Android Design: Notifications</a> + <a href="https://material.google.com/patterns/notifications.html">Material Design: Notifications</a> </li> </ol> </div> @@ -97,7 +97,7 @@ The class {@link android.app.Notification.Builder Notification.Builder} was adde The material design changes introduced in Android 5.0 (API level 21) are of particular importance, and you should review the <a href="{@docRoot}training/material/index.html">Material Design</a> training for more information. To learn how to design notifications and their interactions, -read the <a href="{@docRoot}design/patterns/notifications.html">Notifications</a> design guide.</p> +read the <a href="https://material.google.com/patterns/notifications.html">Notifications</a> design guide.</p> <h2 id="CreateNotification">Creating a Notification</h2> @@ -184,7 +184,7 @@ notification, you pass the {@link android.app.Notification} object to the system </p> <p> For information about setting an appropriate priority level, see "Correctly set and manage notification priority" in the <a - href="{@docRoot}design/patterns/notifications.html">Notifications</a> Design + href="https://material.google.com/patterns/notifications.html">Notifications</a> Design guide. </p> <!-- ------------------------------------------------------------------------------------------ --> @@ -323,7 +323,7 @@ mBuilder.setStyle(inBoxStyle); For example, Gmail notifies the user that new emails have arrived by increasing its count of unread messages and by adding a summary of each email to the notification. This is called "stacking" the notification; it's described in more detail in the - <a href="{@docRoot}design/patterns/notifications.html">Notifications</a> Design guide. + <a href="https://material.google.com/patterns/notifications.html">Notifications</a> Design guide. </p> <p class="note"> <strong>Note:</strong> This Gmail feature requires the "inbox" expanded layout, which is part @@ -886,35 +886,38 @@ method.</p> <h3 id="controllingMedia">Controlling Media Playback on the Lock Screen</h3> -<p>In Android 5.0 (API level 21) the lock screen no longer displays media controls -based on the {@link android.media.RemoteControlClient}, which is now deprecated. Instead, use the -{@link android.app.Notification.MediaStyle} template with the -{@link android.app.Notification.Builder#addAction(android.app.Notification.Action) addAction()} -method, which converts actions into clickable icons.</p> - -<p class="note"><strong>Note:</strong> The template and the -{@link android.app.Notification.Builder#addAction(android.app.Notification.Action) addAction()} -method are not included in the support library, so these features run in Android 5.0 and higher -only.</p> +<p> + In Android 5.0 (API level 21) the lock screen no longer displays media + controls based on the {@link android.media.RemoteControlClient}, which is + now deprecated. Instead, use the {@link + android.support.v7.app.NotificationCompat.MediaStyle} template with the + {@link + android.support.v4.app.NotificationCompat.Builder#addAction(android.support.v4.app.NotificationCompat.Action) + addAction()} method, which converts actions into clickable icons. +</p> -<p>To display media playback controls on the lock screen in Android 5.0, set the visibility -to {@link android.support.v4.app.NotificationCompat#VISIBILITY_PUBLIC}, as described above. Then add -the actions and set the {@link android.app.Notification.MediaStyle} template, as described in the -following sample code:</p> +<p> + To display media playback controls on the lock screen in Android 5.0, set + the visibility to {@link + android.support.v4.app.NotificationCompat#VISIBILITY_PUBLIC}, as described + above. Then add the actions and set the {@link + android.support.v7.app.NotificationCompat.MediaStyle} template, as described + in the following sample code: +</p> <pre> -Notification notification = new Notification.Builder(context) +Notification notification = new NotificationCompat.Builder(context) // Show controls on lock screen even when user hides sensitive content. - .setVisibility(Notification.VISIBILITY_PUBLIC) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setSmallIcon(R.drawable.ic_stat_player) // Add media control buttons that invoke intents in your media service .addAction(R.drawable.ic_prev, "Previous", prevPendingIntent) // #0 .addAction(R.drawable.ic_pause, "Pause", pausePendingIntent) // #1 .addAction(R.drawable.ic_next, "Next", nextPendingIntent) // #2 // Apply the media style template - .setStyle(new Notification.MediaStyle() - .setShowActionsInCompactView(1 /* #1: pause button */) - .setMediaSession(mMediaSession.getSessionToken()) + .setStyle(new NotificationCompat.MediaStyle() + .setShowActionsInCompactView(1 /* #1: pause button */) + .setMediaSession(mMediaSession.getSessionToken())) .setContentTitle("Wonderful music") .setContentText("My Awesome Band") .setLargeIcon(albumArtBitmap) diff --git a/docs/html/guide/topics/ui/settings.jd b/docs/html/guide/topics/ui/settings.jd index 9e304a3f603c..619fd268aef9 100644 --- a/docs/html/guide/topics/ui/settings.jd +++ b/docs/html/guide/topics/ui/settings.jd @@ -943,8 +943,8 @@ uses.</p> <p>The Android framework includes a variety of {@link android.preference.Preference} subclasses that allow you to build a UI for several different types of settings. -However, you might discover a setting you need for which there’s no built-in solution, such as a -number picker or date picker. In such a case, you’ll need to create a custom preference by extending +However, you might discover a setting you need for which there's no built-in solution, such as a +number picker or date picker. In such a case, you'll need to create a custom preference by extending the {@link android.preference.Preference} class or one of the other subclasses.</p> <p>When you extend the {@link android.preference.Preference} class, there are a few important diff --git a/docs/html/images/cards/card-notifications_2x.png b/docs/html/images/cards/card-notifications_2x.png Binary files differnew file mode 100644 index 000000000000..e56c1df34419 --- /dev/null +++ b/docs/html/images/cards/card-notifications_2x.png diff --git a/docs/html/images/tools/sdk-manager-support-libs.png b/docs/html/images/tools/sdk-manager-support-libs.png Binary files differindex 37968005c789..cb4cea5795a6 100644 --- a/docs/html/images/tools/sdk-manager-support-libs.png +++ b/docs/html/images/tools/sdk-manager-support-libs.png diff --git a/docs/html/images/topic/arc/sideload_figure_1.jpg b/docs/html/images/topic/arc/sideload_figure_1.jpg Binary files differnew file mode 100644 index 000000000000..8eb508504185 --- /dev/null +++ b/docs/html/images/topic/arc/sideload_figure_1.jpg diff --git a/docs/html/jd_collections.js b/docs/html/jd_collections.js index 03efa86ffaaa..3ceddf2c756d 100644 --- a/docs/html/jd_collections.js +++ b/docs/html/jd_collections.js @@ -857,8 +857,7 @@ var RESOURCE_COLLECTIONS = { "design/index.html", "design/patterns/navigation.html", "design/patterns/actionbar.html", - "design/style/iconography.html", - "design/patterns/notifications.html" + "design/style/iconography.html" ] }, "distribute/essentials/corequalityguidelines/functionality": { @@ -1076,7 +1075,6 @@ var RESOURCE_COLLECTIONS = { "distribute/getusers/notifications": { "title": "", "resources": [ - "design/patterns/notifications.html", "distribute/engage/gcm.html", "https://play.google.com/about/developer-content-policy.html" ] @@ -1181,8 +1179,7 @@ var RESOURCE_COLLECTIONS = { "resources": [ "distribute/essentials/optimizing-your-app.html", "distribute/tools/launch-checklist.html", - "distribute/googleplay/developer-console.html", - "design/patterns/notifications.html" + "distribute/googleplay/developer-console.html" ] }, "distribute/engage/video/more": { diff --git a/docs/html/jd_extras_en.js b/docs/html/jd_extras_en.js index 5c4227781de2..ef94cc415a5a 100644 --- a/docs/html/jd_extras_en.js +++ b/docs/html/jd_extras_en.js @@ -2655,6 +2655,19 @@ METADATA['en'].extras = METADATA['en'].extras.concat([ "lang": "en", "group": "", "tags": [], + "url": "https://material.google.com/patterns/notifications.html", + "timestamp": "1469639720", + "image": "images/cards/card-notifications_2x.png", + "title": "Notifications", + "summary": "Notifications inform your app’s users about relevant and timely events in your app.", + "keywords": ["notifications", "design"], + "type": "design", + "category": "material design" + }, + { + "lang": "en", + "group": "", + "tags": [], "url": "https://www.google.com/design/spec/usability/", "timestamp": null, "image": "images/cards/material-usability_2x.png", @@ -2733,7 +2746,6 @@ METADATA['en'].extras = METADATA['en'].extras.concat([ "type": "design", "category": "material design" }, - { "lang": "en", "group": "", @@ -4672,7 +4684,7 @@ METADATA['en'].collections = { "design/patterns/navigation.html", "design/patterns/actionbar.html", "design/style/iconography.html", - "design/patterns/notifications.html" + "https://material.google.com/patterns/notifications.html" ] }, "distribute/essentials/corequalityguidelines/functionality": { @@ -4869,7 +4881,7 @@ METADATA['en'].collections = { "distribute/getusers/notifications": { "title": "", "resources": [ - "design/patterns/notifications.html", + "https://material.google.com/patterns/notifications.html", "distribute/engage/gcm.html", "https://play.google.com/about/developer-content-policy.html" ] @@ -4985,7 +4997,7 @@ METADATA['en'].collections = { "distribute/essentials/optimizing-your-app.html", "distribute/tools/launch-checklist.html", "distribute/googleplay/developer-console.html", - "design/patterns/notifications.html" + "https://material.google.com/patterns/notifications.html" ] }, "distribute/engage/video/more": { diff --git a/docs/html/topic/arc/_book.yaml b/docs/html/topic/arc/_book.yaml new file mode 100644 index 000000000000..42287a7c8587 --- /dev/null +++ b/docs/html/topic/arc/_book.yaml @@ -0,0 +1,9 @@ +toc: +- title: Optimizing Apps for Chromebooks + path: /topic/arc/index.html +- title: App Manifest Compatibility for Chromebooks + path: /topic/arc/manifest.html +- title: Loading Apps on Chromebooks + path: /topic/arc/sideload.html +- title: Chrome OS Device Support for Apps + path: /topic/arc/device-support.html diff --git a/docs/html/topic/arc/device-support.jd b/docs/html/topic/arc/device-support.jd new file mode 100644 index 000000000000..fc471acb05a5 --- /dev/null +++ b/docs/html/topic/arc/device-support.jd @@ -0,0 +1,153 @@ +page.title=Chrome OS Device Support for Apps +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>On this page</h2> + + <ol> + <li><a href="#overview">Overview</a></li> + <li><a href="#support">Supported Platforms</a></li> + </ol> + </div> + </div> + +<p> +You can use the Google Play Store to install Android apps on several Google +Chromebooks. This document describes the Chromebooks, Chromeboxes, and +Chromebases that can install Android apps, both currently and in upcoming +releases of Chrome OS. +</p> + +<h2 id="overview">Overview</h2> + +<p> +The same Android apps that run on phones and tablets can run on Chromebooks +without compromising their speed, simplicity, or security. To develop the best +experience for Android apps across Chromebooks, you should test your app on a +suite of devices that consists of the following categories: +</p> + +<ul> + <li> + ARM architecture. + </li> + <li> + Intel x86 architecture. + </li> + <li> + Touch. + </li> + <li> + Non-touch (uses fake-touch). + </li> + <li> + Convertible. + </li> +</ul> + +<p>To learn more about Google Play Store support on Chromebooks, see the +following <a class="external-link" +href="https://chrome.googleblog.com/2016/05/the-google-play-store-coming-to.html"> +Google Chrome blog post</a>. +</p> + +<p class="note"><strong>Note: </strong>You may elect to exclude your app from +being available to certain Android devices, such as Chromebooks. For more +information, visit <a class="external-link" +href="https://support.google.com/googleplay/android-developer/answer/1286017"> +View & restrict your app's compatible devices</a>. +</p> + +<p> +The following section lists the Chromebooks that work with Android apps and the +categories that each device satisfies. +</p> + +<h2 id="support">Supported Platforms</h2> + +<p> +Android apps are not available on every Chromebook, but Google continues to +evaluate more devices based on a range of factors, such as processor type, GPU, +and drivers. The following table shows the platforms that currently support +Android apps: +</p> + +<p class="table-caption" id="Objects-and-interfaces"> + <strong>Table 1.</strong> Chromebooks that currently support Android apps.</p> +<table> + <tr> + <th scope="col">Manufacturer</th> + <th scope="col">Model</th> + <th scope="col">Architecture</th> + <th scope="col">Touchscreen support</th> + <th scope="col">Convertible</th> + </tr> + <tr> + <td>Acer</td> + <td>Chromebook R11 / C738T</td> + <td>Intel x86</td> + <td>Yes</td> + <td>Yes</td> + </tr> + <tr> + <td>Asus</td> + <td>Chromebook Flip</td> + <td>ARM</td> + <td>Yes</td> + <td>Yes</td> + </tr> + <tr> + <td>Google</td> + <td>Chromebook Pixel (2015)</td> + <td>Intel x86</td> + <td>Yes</td> + <td>No</td> + </tr> +</table> + +<p> +The following list shows the platforms that will support Android apps in an +upcoming release of Chrome OS: +</p> + +<ul> + <li><strong>Acer: </strong>Chromebook 11 C740, Chromebook 11 CB3-111 / C730 / + C730E / CB3-131, Chromebook 14 CB3-431, Chromebook 14 for Work, Chromebook + 15 CB5-571 / C910, Chromebook 15 CB3-531, Chromebox CXI2, Chromebase 24 + </li> + <li><strong>Asus: </strong>Chromebook C200, Chromebook C201, + Chromebook C202SA, Chromebook C300SA, Chromebook C300, Chromebox CN62, + Chromebit CS10</li> + <li><strong>AOpen: </strong>Chromebox Commercial, + Chromebase Commercial 22"</li> + <li><strong>Bobicus: </strong>Chromebook 11</li> + <li><strong>CDI: </strong>eduGear Chromebook K Series, + eduGear Chromebook M Series, eduGear Chromebook R Series</li> + <li><strong>CTL: </strong>Chromebook J2 / J4, N6 Education Chromebook, + J5 Convertible Chromebook</li> + <li><strong>Dell: </strong>Chromebook 11 3120, Chromebook 13 7310</li> + <li><strong>Edxis: </strong>Chromebook, Education Chromebook</li> + <li><strong>Haier: </strong>Chromebook 11, Chromebook 11e, Chromebook 11 G2 + </li> + <li><strong>Hexa: </strong>Chromebook Pi</li> + <li><strong>HiSense: </strong>Chromebook 11</li> + <li><strong>Lava: </strong>Xolo Chromebook</li> + <li><strong>HP: </strong>Chromebook 11 G3 / G4 / G4 EE, Chromebook 14 G4, + Chromebook 13</li> + <li><strong>Lenovo: </strong>100S Chromebook, N20 / N20P Chromebook, + N21 Chromebook, ThinkCentre Chromebox, ThinkPad 11e Chromebook, + N22 Chromebook, Thinkpad 13 Chromebook, Thinkpad 11e Chromebook Gen 3</li> + <li><strong>Medion: </strong>Akoya S2013, Chromebook S2015</li> + <li><strong>M&A: </strong>Chromebook</li> + <li><strong>NComputing: </strong>Chromebook CX100</li> + <li><strong>Nexian: </strong>Chromebook 11.6"</li> + <li><strong>PCMerge: </strong>Chromebook PCM-116E</li> + <li><strong>Poin2: </strong>Chromebook 11</li> + <li><strong>Samsung: </strong>Chromebook 2 11" - XE500C12, Chromebook 3</li> + <li><strong>Sector 5: </strong>E1 Rugged Chromebook</li> + <li><strong>Senkatel: </strong>C1101 Chromebook</li> + <li><strong>Toshiba: </strong>Chromebook 2, Chromebook 2 (2015)</li> + <li><strong>True IDC: </strong>Chromebook 11</li> + <li><strong>Viglen: </strong>Chromebook 11</li> +</ul> diff --git a/docs/html/topic/arc/index.jd b/docs/html/topic/arc/index.jd new file mode 100644 index 000000000000..d46fbc89ac59 --- /dev/null +++ b/docs/html/topic/arc/index.jd @@ -0,0 +1,398 @@ +page.title=Optimizing Apps for Chromebooks +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>On this page</h2> + + <ol> + <li><a href="#update-manifest">Update Your App's Manifest File</a></li> + <li><a href="#leverage">Leverage Support for Multi-Window Mode</li> + <li><a href="#keyboard">Support the Keyboard, Trackpad, and Mouse</a></li> + <li><a href="#backup">Use Backup and Restore Effectively</a></li> + <li><a href="#update-ndk">Update the NDK Libraries</a></li> + <li><a href="#support-new-features">Plan Support for New Android Features</a></li> + <li><a href="#testing">Test Your App</a></li> + <li><a href="#setup">Set Up ADB</a></li> + <li><a href="#learning-materials">Additional Learning Materials</a></li> + </ol> + </div> + </div> + +<p> +Google Chromebooks now support the Google Play Store and Android apps. This +document describes some ways that you can optimize your Android apps for +Chromebooks. +</p> + +<h2 id="update-manifest">Update Your App's Manifest File</h2> + +<p> +To begin optimizing your Android app for Chromebooks, update your manifest file +(<code>AndroidManifest.xml</code>) to account for some key hardware and software +differences between Chromebooks and other devices running Android. +</p> + +<p> +As of Chrome OS version M53, all Android apps that don't explicitly require the +<a +href="{@docRoot}guide/topics/manifest/uses-feature-element.html#touchscreen-hw-features"><code>android.hardware.touchscreen</code></a> +feature will also work on Chrome OS devices that support the +<code>android.hardware.faketouch</code> feature. However, if you want your app +to work on all Chromebooks in the best possible way, go to your manifest file +and adjust the settings so that the <code>android.hardware.touchscreen</code> +feature is not required, as shown in the following example. You should also +review your mouse and keyboard interactions. +</p> + +<pre> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + ... > + <!-- Some Chromebooks don't support touch. Although not essential, + it's a good idea to explicitly include this declaration. --> + <uses-feature android:name="android.hardware.touchscreen" + required="false" /> +</manifest> +</pre> + +<p> +Different devices often have different sensors available in them. See the <a +href="https://developer.android.com/guide/topics/sensors/sensors_overview.html">Sensors +Overview</a> document for an overview of all sensors that the Android platform +supports. Although Android handheld devices may have GPS and accelerometers, +sensors are not guaranteed to be available in every Chromebook. However, there +are cases where the functionality of a sensor is provided in another way. For +example, Chromebooks may not have GPS sensors, but they still provide location +data based on Wi-Fi connections. If you want your app to run on Chromebooks, +regardless of sensor support, you should update your manifest file so that none +of the sensors are required. +</p> + +<p class="note"><strong>Note</strong>: If you don't require a particular sensor +for your app but still use measurements from the sensor when it's available, +make sure you dynamically check for the sensor's availability before trying to +gather information from it in your app. +</p> + +<p> +Some software features are unsupported on Chromebooks. For example, apps that +provide custom IMEs, app widgets, live wallpapers, and app launchers aren't +supported and won't be available for installation on Chromebooks. For a complete +list of software features that aren't currently supported on Chromebooks, see <a +href="{@docRoot}topic/arc/manifest.html#incompat-software-features">incompatible +software features</a>. +</p> + +<h2 id="leverage">Leverage Support for Multi-Window Mode</h2> + +<p> +The implementation of Android apps on Chrome OS includes basic multi-window +support. Instead of automatically drawing over the full screen, Android renders +apps on Chrome OS into layouts that are appropriate for this form factor. Google +provides support for the most common window layouts: + +<ul> + <li> + <strong>Portrait</strong> – Similar to Nexus 5. + </li> + <li> + <strong>Landscape</strong> – Similar to Nexus 7. + </li> + <li> + <strong>Maximized</strong> – Uses all available screen pixels. + </li> +</ul> + +<p> +In addition, end users are presented with window controls to toggle among all +available layouts. By choosing the correct orientation option, you can ensure +that the user has the correct layout upon launching the app. If an app is +available in portrait and landscape, it defaults to landscape if possible. After +this option is set, it is remembered on a per-app basis. Google recommends that +you test your app to ensure that it handles changes in window size +appropriately. +</p> + +<h2 id="keyboard">Support the Keyboard, Trackpad, and Mouse</h2> + +<p> +All Chromebooks have a physical keyboard and a trackpad, and some Chromebooks +have a touchscreen as well. Some devices can even convert from a laptop to a +tablet. +</p> + +<p> +Many existing apps already support mouse and trackpad interactions with no extra +work required. However, it's always best to adjust your app's behavior +appropriately when users interact with it using a trackpad instead of a +touchscreen, and you should support and distinguish between both interfaces +properly. Given the support for physical keyboards, you can now provide hotkeys +to enable your app's users to be more productive. For example, if your app +supports printing, you can use <strong>Ctrl+P</strong> to open a print dialog. +</p> + +<h2 id="backup">Use Backup and Restore Effectively</h2> + +<p> +One of the strongest features of Chromebooks is that users can easily migrate +from one device to another. That is, if someone stops using one Chromebook and +starts using another, they simply have to sign in, and all of their apps appear. +</p> + +<p class="note"><strong>Tip: </strong> Although it's not mandatory, backing up +your app's data to the cloud is a good idea. +</p> + +<p> +Chromebooks can also be shared among a large number of people, such as in +schools. Since local storage is not infinite, entire accounts—together +with their storage—can be removed from the device at any point. For +educational settings, it's a good idea to keep this scenario in mind. +</p> + +<h2 id="update-ndk">Update the NDK Libraries</h2> + +<p> +If your app uses the Android NDK libraries, and its target SDK version is 23 or +higher, ensure that text relocations are removed from both the ARM and x86 +versions of your NDK libraries, as they're not compatible in Android 6.0 (API +level 23) and higher. By leaving text relocations in your NDK libraries, you may +also cause incompatibility errors with Chromebooks, especially when running on +a device that uses an x86 architecture. +</p> + +<p class="note"><strong>Note: </strong>To view more details on updating NDK +libraries properly, see the <a +href="https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-runtime"> +Runtime</a> section of the Android 6.0 Changes document. +</p> + +<h2 id="support-new-features">Plan Support for New Android Features</h2> + +<p> +Android apps on Chromebooks initially ship with APIs for Android 6.0 (API level +23). By following the best practices outlined above, your app is likely to be +compatible with the multi-window improvements introduced in Android 7.0 (API +level 24). It's good to plan support for the APIs and behaviors available as of +Android 7.0, which feature several improvements. For example, multi-window +support is better integrated, and you're able to resize activities arbitrarily, +making them feel more natural. You can also access APIs for drag-and-drop +operations across apps and mouse cursor control. +</p> + +<h2 id="testing">Test Your App</h2> + +<p> +To <a href="{@docRoot}topic/arc/sideload.html">load</a> your app onto your +Chromebook for testing, you must enter <em>Developer</em> mode on your Chrome OS +device and enable <em>unknown sources</em>. See the <a class="external-link" +href="https://www.chromium.org/chromium-os/poking-around-your-chrome-os-device#TOC-Putting-your-Chrome-OS-Device-into-Developer-Mode"> +Putting your Chrome OS Device into Developer Mode</a> document for detailed +instructions about moving your device into Developer mode. After your device is +in Developer mode, you can go to your Chrome settings and select <strong>Enable +Unknown Sources</strong> under the <em>security in app</em> settings. +</p> + +<p> +After enabling Developer mode, you can load an Android app onto your Chrome OS +device using one of several methods. For more details, see the <a +href="{@docRoot}topic/arc/sideload.html#load-app">Load Your App</a> section of +the Loading Apps on Chromebooks page. +</p> + +<p class="note"><strong>Note: </strong>To ensure that your Android app works +well on a variety of Chromebook devices and available form factors, Google +recommends that you test your app on an ARM-based Chromebook, an x86-based +Chromebook, a device with a touchscreen and one without one, and on a +convertible device (one that can change between a laptop and a tablet). To view +the full list of supported devices, see the <a +href="{@docRoot}topic/arc/device-support.html">Chrome OS Device Support for +Apps</a> page.</p> + +<h2 id="setup">Set Up ADB</h2> + +<p> +Before attempting to set up an ADB connection, you must start your Chrome OS in +<a class="external-link" +href="https://www.chromium.org/chromium-os/poking-around-your-chrome-os-device"> +Developer Mode</a> so that you have the ability to install Android apps on the +Chromebook. +</p> + +<p class="caution"><strong>Caution: </strong>After switching your Chrome OS +device to Developer mode, it restarts and clears all existing data on the +device. +</p> + +<p> +To set up ADB, complete the following steps: +</p> + +<ol> + <li> + Press <strong>Ctrl+D</strong> to start your device. + </li> + <li> + Finish the setup process. + </li> + <li> + Log into your test account. + </li> + <li> + Accept the Google Play Store terms and service conditions. + </li> +</ol> + +<h3>Configure the firewall</h3> + +<p> +To configure the Chrome OS firewall to allow incoming ADB connections, complete +the following steps: +</p> + +<ol> + <li> + Press <strong>Ctrl+Alt+T</strong> to start the Chrome OS terminal. + </li> + <li> + Type <strong>shell</strong> to get to the bash command shell: +<pre class="no-pretty-print"> +crosh> shell +chronos@localhost / $ +</pre> + </li> + <li> + Type the following commands to set up developer features and enable + disk-write access for the firewall settings changes: +<pre class="no-pretty-print"> +chronos@localhost / $ sudo /usr/libexec/debugd/helpers/dev_features_rootfs_verification +chronos@localhost / $ sudo reboot +</pre> + The <em>sudo reboot</em> command restarts your Chromebook. +<p class="note"><strong>Note</strong>: You can press the <strong>Tab</strong> +key to enable autocompletion of file names.</p> + </li> + <li> + After your device restarts, log in to your test account and type the + following command to enable the <em>secure shell</em> and configure the + firewall properly: +<pre class="no-pretty-print"> +chronos@localhost / $ sudo /usr/libexec/debugd/helpers/dev_features_ssh +</pre> + You can now exit out of the shell. + </li> +</ol> + +<p class="note"><strong>Note</strong>: You must complete this procedure only +once on your Chromebook.</p> + +<h3>Check the IP address of your Chromebook</h3> + +<p> +To verify the IP address of your Chromebook, complete the following steps: +</p> + +<ol> + <li> + Click the clock icon in the bottom-right area of the screen. + </li> + <li> + Click <strong>Settings</strong>. + </li> + <li> + The <em>Internet Connection</em> section in the Settings area lists all of + the available networks. Select the one that you want to use for ADB. + </li> + <li> + Take note of the IP address that appears. + </li> +</ol> + +<h3>Enable ADB debugging</h3> + +<p> +To enable ADB debugging, complete the following steps: +</p> + +<ol> + <li> + Click the clock icon in the bottom-right area of the screen. + </li> + <li> + Click <strong>Settings</strong>. + </li> + <li> + In the <em>Android Apps</em> section, click the <strong>Settings</strong> + link in the line that reads <em>Manage your Android apps in Settings</em>. + This brings up the Android apps settings. + </li> + <li> + Click <strong>About device</strong>. + </li> + <li> + Click <strong>Build number</strong> seven times to move into Developer mode. + </li> + <li> + Click the arrow in the top-left area of the window to go back to the main + Settings screen. + </li> + <li> + Click the new <strong>Developer options</strong> item, activate <strong>ADB + debugging</strong>, and then click <strong>OK</strong> to allow ADB + debugging. + </li> + <li> + Return to your development machine and use ADB to connect to your + Chromebook's using its IP address and port 22. + </li> + <li> + On your Chromebook, click <strong>Allow</strong> when prompted whether you + want to allow the debugger. Your ADB session is established. + </li> +</ol> + +<h4>Troubleshooting ADB debugging</h4> + +<p> +Sometimes the ADB device shows that it's offline when everything is connected +properly. In this case, complete the following steps to troubleshoot the issue: +</p> + +<ol> + <li> + Deactivate <strong>ADB debugging</strong> in <em>Developer options</em>. + </li> + <li> + In a terminal window, run <code>adb kill-server</code>. + </li> + <li> + Re-activate the <strong>ADB debugging</strong> option. + </li> + <li> + In a terminal window, attempt to run <code>adb connect</code>. + </li> + <li> + Click <strong>Allow</strong> when prompted whether you want to allow + debugging. Your ADB session is established. + </li> +</ol> + +<h2 id="learning-materials">Additional Learning Materials</h2> + +<p> +To learn more about optimizing your Android apps for Chromebooks, consult the +following resources: +</p> + +<ul> + <li> + Review the + <a class="external-link" href="http://android-developers.blogspot.com/2016/05/bring-your-android-app-to-chromebooks.html"> + Bring your Android App to Chromebooks</a> I/O session. + </li> + <li> + Post a question on the <a class="external-link" + href="https://plus.sandbox.google.com/+AndroidDevelopers">Android developer + community</a> with hashtag <em>#AndroidAppsOnChromeOS</em>. + </li> +</ul> diff --git a/docs/html/topic/arc/manifest.jd b/docs/html/topic/arc/manifest.jd new file mode 100644 index 000000000000..7d1866591ab3 --- /dev/null +++ b/docs/html/topic/arc/manifest.jd @@ -0,0 +1,341 @@ +page.title=App Manifest Compatibility for Chromebooks +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>On this page</h2> + + <ol> + <li><a href="#incompat-entries">Incompatible Manifest Entries</a></li> + <li> + <a href="#implied-features">Permissions That Imply Feature + Requirements</a> + </li> + </ol> + </div> + </div> + +<p> +As you prepare your Android app to run on Chromebooks, you should consider the +device features that your app uses. Chromebooks don't support all of the +hardware and software features that are available on other devices running +Android. If your app requires specific features that aren't supported on +Chromebooks, it won't be available for installation on Chromebooks. +</p> + +<p> +You declare your app's requirements for hardware features and certain software +features in the <a +href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest file</a>. +This document describes the app manifest feature declarations that aren't +compatible with Chromebooks. +</p> + +<h2 id="incompat-entries">Incompatible Manifest Entries</h2> + +<p> +The manifest entries listed in this section aren't currently compatible with +Chromebooks. If your app uses any of these entries, consider removing them or +including the <code>required="false"</code> attribute value with them so that +your app can be installed on Chromebooks. For more information about declaring +feature use without requiring that the feature be available on the device, see +the guide for the <a +href="{@docRoot}guide/topics/manifest/uses-feature-element.html#market-feature-filtering"> +<code><uses-feature></code></a> manifest element. +</p> + +<p class="note"><strong>Note</strong>: See the <a +href="{@docRoot}guide/topics/manifest/uses-feature-element.html#features-reference"> +Features Reference</a> for a complete list of app manifest features and +descriptions. +</p> + +<h3 id="incompat-hardware-features">Hardware features</h3> + +<p> +Support for hardware features varies on Chromebooks. Some features aren't +supported on any Chromebooks while others are supported on some Chromebooks. +</p> + +<h4>Unsupported hardware features</h4> + +<p> +The following list includes the hardware features that aren't currently +supported on Chromebooks: +</p> + +<ul> + <li> + <code>android.hardware.camera</code> – Back-facing camera + </li> + <li> + <code>android.hardware.camera.autofocus</code> – Camera that uses + autofocus + </li> + <li> + <code>android.hardware.camera.capability.manual_post_processing</code> + – Camera that uses the <code>MANUAL_POST_PROCESSING</code> feature, + including functionality for overriding auto white balance + </li> + <li> + <code>android.hardware.camera.capability.manual_sensor</code> – Camera + that uses the <code>MANUAL_SENSOR</code> feature, including auto-exposure + locking support + </li> + <li> + <code>android.hardware.camera.capability.raw</code> – Camera that uses + the <code>RAW</code> feature, including the ability to save DNG (raw) files + and provide DNG-related metadata + </li> + <li> + <code>android.hardware.camera.flash</code> – Camera that uses flash + </li> + <li> + <code>android.hardware.camera.level.full</code> – Camera that uses + <code>FULL</code>-level image-capturing support + </li> + <li> + <code>android.hardware.consumerir</code> – Infrared (IR) + </li> + <li> + <code>android.hardware.location.gps</code> – GPS + </li> + <li> + <code>android.hardware.nfc</code> – Near-Field Communication (NFC) + </li> + <li> + <code>android.hardware.nfc.hce</code> – NFC card emulation + (<em>deprecated</em>) + </li> + <li> + <code>android.hardware.sensor.barometer</code> – Barometer (air + pressure) + </li> + <li> + <code>android.hardware.telephony</code> – Telephony, including radio + with data communication services + </li> + <li> + <code>android.hardware.telephony.cdma</code> – Telephony Code Division + Multiple Access (CDMA) network support + </li> + <li> + <code>android.hardware.telephony.gsm</code> – Telephony Global System + for Mobile Communications (GSM) network support + </li> + <li> + <code>android.hardware.type.automotive</code> – Android Auto user + interface + </li> + <li> + <code>android.hardware.type.television</code> – Television + (<em>deprecated</em>) + <li> + <code>android.hardware.usb.accessory</code> – USB accessory mode + </li> + <li> + <code>android.hardware.usb.host</code> – USB host mode + </li> +</ul> + +<h4>Partially-supported hardware features</h4> + +<p> +The following list includes the hardware features that may be available on some +Chromebooks: +</p> + +<ul> + <li> + <code>android.hardware.sensor.accelerometer</code> – Accelerometer + (device orientation) + </li> + <li> + <code>android.hardware.sensor.compass</code> – Compass + </li> + <li> + <code>android.hardware.sensor.gyroscope</code> – Gyroscope (device + rotation and twist) + </li> + <li> + <code>android.hardware.sensor.light</code> – Light + </li> + <li> + <code>android.hardware.sensor.proximity</code> – Proximity (to user) + </li> + <li> + <code>android.hardware.sensor.stepcounter</code> – Step counter + </li> + <li> + <code>android.hardware.sensor.stepdetector</code> – Step detector + </li> +</ul> + +<h4>Touchscreen hardware support</h4> + +<p> +As of Chrome OS version M53, all Android apps that don't explicitly require the +<a href="{@docRoot}guide/topics/manifest/uses-feature-element.html#touchscreen-hw-features"> +<code>android.hardware.touchscreen</code></a> feature will also work on Chrome +OS devices that support the <a +href="{@docRoot}guide/topics/manifest/uses-feature-element.html#touchscreen-hw-features"> +<code>android.hardware.faketouch</code></a> feature. Devices that have fake +touch interfaces provide a user input system that emulates basic touch events. +For example, the user could interact with a mouse or remote control to move an +on-screen cursor, scroll through a list, and drag elements from one part of the +screen to another. +</p> + +<p> +If you don't want your app to be installed on devices that have fake touch +interfaces but not touchscreens, you can complete one of the following actions: +</p> + +<ul> + <li>Exclude specific devices in the <a class="external-link" + href="https://play.google.com/apps/publish">Google Play Developer Console.</a> + </li> + <li>Filter devices with no touchscreen hardware by explicitly declaring <a + href="{@docRoot}guide/topics/manifest/uses-feature-element.html#touchscreen-hw-features"> + <code>android.hardware.touchscreen</code></a> as being required in order to + install your app.</li> +</ul> + +<h3 id="incompat-software-features">Software features</h3> + +<p> +The following list includes the software features that aren't currently +supported on Chromebooks: +</p> + +<ul> + <li> + <code>android.software.app_widgets</code> – App Widgets on the Home + screen + </li> + <li> + <code>android.software.device_admin</code> – Device policy + administration + </li> + <li> + <code>android.software.home_screen</code> – Replaces device's Home + screen + </li> + <li> + <code>android.software.input_methods</code> – Custom input methods + (instances of <a href="{@docRoot}reference/android/inputmethodservice/InputMethodService.html"> + <code>InputMethodService</code></a>) + </li> + <li> + <code>android.software.leanback</code> – UI designed for large-screen + viewing + </li> + <li> + <code>android.software.live_wallpaper</code> – Animated wallpapers + </li> + <li> + <code>android.software.live_tv</code> – Streaming live TV programs + </li> + <li> + <code>android.software.managed_users</code> – Secondary users and + managed profiles + </li> + <li> + <code>android.software.midi</code> – Musical Instrument Digital + Interface (MIDI) protocol, which supports connecting to musical instruments + and providing sound + </li> + <li> + <code>android.software.sip</code> – Session Initiation Protocol (SIP) + service, which supports video conferencing and instant messaging + </li> + <li> + <code>android.software.sip.voip</code> – Voice Over Internet Protocol + (VoIP) service based on SIP, which supports two-way video conferencing + </li> +</ul> + +<h2 id="implied-features">Permissions That Imply Feature Requirements</h2> + +<p> +Some permissions that you request in your manifest files can create implied +requests for hardware and software features. By requesting these permissions, +you'll prevent your app from being installed on Chromebooks. +</p> + +<p> +For details about how to prevent permission requests from making your app +unavailable on Chromebooks, see the <a href="#incompat-entries">Incompatible +Manifest Entries</a> section of this page. +</p> + +<p> +The following table shows the permissions that imply certain feature +requirements which make an app incompatible with Chromebooks: +</p> + +<p class="table-caption"> +<strong>Table 1. </strong>Device permissions that imply hardware features which +are incompatible with Chromebooks. +</p> + +<table> + <tr> + <th scope="col">Category</th> + <th scope="col">This Permission...</th> + <th scope="col">...Implies This Feature Requirement</th> + </tr> + <tr> + <td>Camera</td> + <td><code>CAMERA</code></td> + <td> + <code>android.hardware.camera</code> and<br> + <code>android.hardware.camera.autofocus</code> + </td> + </tr> + <tr> + <td rowspan="11">Telephony</td> + <td><code>CALL_PHONE</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> + <tr> + <td><code>CALL_PRIVILEGED</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> + <tr> + <td><code>MODIFY_PHONE_STATE</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> + <tr> + <td><code>PROCESS_OUTGOING_CALLS</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> + <tr> + <td><code>READ_SMSREAD_SMS</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> + <tr> + <td><code>RECEIVE_SMS</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> + <tr> + <td><code>RECEIVE_MMS</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> + <tr> + <td><code>RECEIVE_WAP_PUSH</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> + <tr> + <td><code>SEND_SMS</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> + <tr> + <td><code>WRITE_APN_SETTINGS</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> + <tr> + <td><code>WRITE_SMS</code></td> + <td><code>android.hardware.telephony</code></td> + </tr> +</table> diff --git a/docs/html/topic/arc/sideload.jd b/docs/html/topic/arc/sideload.jd new file mode 100644 index 000000000000..dca84ffc65ca --- /dev/null +++ b/docs/html/topic/arc/sideload.jd @@ -0,0 +1,125 @@ +page.title=Loading Apps on Chromebooks +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>On this page</h2> + + <ol> + <li><a href="#enter-dev">Enter Developer Mode</a></li> + <li><a href="#enable-unknown">Enable Unknown Sources</a></li> + <li><a href="#load-app">Load Your App</a></li> + </ol> + </div> + </div> + +<p> +This document describes how to enter <em>Developer</em> mode and enable +<em>unknown resources</em> so that you can load Android apps on your Google +Chromebook. +</p> + +<h2 id="enter-dev">Enter Developer Mode</h2> + +<p> +To load Android apps, you must enable unknown sources. Enabling unknown sources +is available only when your device is in Developer mode. +</p> + +<p class="caution"><strong>Caution: </strong>Modifications that you make to the +system are not supported by Google and may void your warranty. Additionally, +modifications may cause hardware, software, or security issues. +</p> + +<p class="note"><strong>Note: </strong>On most devices, both the +<em>recovery</em> button and the <em>dev-switch</em> button are virtualized. If +these instructions don't work for you, see the <a class="external-link" +href="https://www.chromium.org/chromium-os/developer-information-for-chrome-os-devices"> +specific instructions for your device</a>. +</p> + +<p> +To enter Developer mode, complete these steps: +</p> + +<ol> + <li> + Invoke <em>Recovery</em> mode by pressing and holding the + <strong>Esc</strong> and <strong>Refresh (F3)</strong> keys, then pressing + the <strong>Power</strong> button. + </li> + <li> + When the <em>Recovery</em> screen appears, press <strong>Ctrl+D</strong>. + There's no prompt for this action, so you must simply complete it. + Afterwards, you are prompted to confirm and reboot into Developer mode. + </li> +</ol> + +<p> +If you see one of the following screens when you turn on your device, you've +successfully entered Developer mode: +</p> + +<img src="{@docRoot}images/topic/arc/sideload_figure_1.jpg" /> + +<p class="img-caption"><strong>Figure 1. </strong>Developer mode confirmation +screens.</p> + +<p class="note"><strong>Note</strong>: To skip the OS loading screen, either +wait 30 seconds or press <strong>Ctrl+D</strong>, and your Chromebook continues +starting. +</p> + +<h2 id="enable-unknown">Enable Unknown Sources</h2> + +<p> +To enable unknown sources, navigate to <strong>Chrome Settings > App Settings > +Security</strong>, then enable <strong>Unknown sources</strong> by moving the +slider to the right. +</p> + +<p class="note"><strong>Note:</strong>You can enable unknown sources only when +your device is in <a +href="{@docRoot}topic/arc/sideload.html#enter-dev">Developer mode</a>. +</p> + +<h2 id="load-app">Load Your App</h2> + +<p> +After enabling unknown sources, you can load apps by copying an app's APK file +to the <em>Downloads</em> folder and opening it with Android's File Manager app. + +</p> + +<p> +You can copy the APK file to your Chromebook using one of the following methods: +</p> + +<ul> + <li> + <strong>Using a cloud app</strong> – Upload your APK file to Google + Drive or send it to yourself via email. Open it with the Android app + equivalent (Drive and Gmail, respectively). + </li> + <li> + <strong>Using an external storage device</strong> – Transfer the APK + file to the Downloads folder of your Chromebook using a thumb drive, SD + card, or an external hard drive. Afterwards, open the Android File Manager + app by navigating to <strong>Chrome Settings > App Settings > Device & + USB > Explore</strong>. + </li> + <li> + <strong>Using ADB</strong> – After <a + href="{@docRoot}topic/arc/index.html#setup"> setting up ADB</a> on your + Chromebook, enter the following command into a terminal window on your + development workstation: +<pre class="no-pretty-print"> +adb install <var>app-name</var>.apk +</pre> + <p>This command pushes the app to your connected Chromebook and installs the + app. For more information about copying and installing apps from a + development computer, see <a + href="{@docRoot}studio/command-line/adb.html#move">Installing an + Application</a>.</p> + </li> +</ul> diff --git a/docs/html/topic/libraries/data-binding/index.jd b/docs/html/topic/libraries/data-binding/index.jd index ec6e58c15ca1..454bb59e7983 100644 --- a/docs/html/topic/libraries/data-binding/index.jd +++ b/docs/html/topic/libraries/data-binding/index.jd @@ -246,21 +246,21 @@ android { </pre> <p> Expressions within the layout are written in the attribute properties using - the “<code>&commat;{}</code>” syntax. Here, the TextView’s text is set to + the "<code>@{}</code>" syntax. Here, the TextView's text is set to the firstName property of user: </p> <pre> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" - android:text="&commat;{user.firstName}"/> + android:text="@{user.firstName}"/> </pre> <h3 id="data_object"> Data Object </h3> <p> - Let’s assume for now that you have a plain-old Java object (POJO) for User: + Let's assume for now that you have a plain-old Java object (POJO) for User: </p> <pre> @@ -296,8 +296,8 @@ public class User { </pre> <p> From the perspective of data binding, these two classes are equivalent. The - expression <strong><code>&commat;{user.firstName}</code></strong> used - for the TextView’s <strong><code>android:text</code></strong> attribute will + expression <strong><code>@{user.firstName}</code></strong> used + for the TextView's <strong><code>android:text</code></strong> attribute will access the <strong><code>firstName</code></strong> field in the former class and the <code>getFirstName()</code> method in the latter class. Alternatively, it will also be resolved to <code>firstName()</code> if that @@ -310,10 +310,10 @@ public class User { <p> By default, a Binding class will be generated based on the name of the layout - file, converting it to Pascal case and suffixing “Binding” to it. The above + file, converting it to Pascal case and suffixing "Binding" to it. The above layout file was <code>main_activity.xml</code> so the generate class was <code>MainActivityBinding</code>. This class holds all the bindings from the - layout properties (e.g. the <code>user</code> variable) to the layout’s Views + layout properties (e.g. the <code>user</code> variable) to the layout's Views and knows how to assign values for the binding expressions.The easiest means for creating the bindings is to do it while inflating: </p> @@ -328,7 +328,7 @@ protected void onCreate(Bundle savedInstanceState) { } </pre> <p> - You’re done! Run the application and you’ll see Test User in the UI. + You're done! Run the application and you'll see Test User in the UI. Alternatively, you can get the view via: </p> @@ -434,15 +434,15 @@ public class Presenter { </pre> Then you can bind the click event to your class as follows: <pre> - <?xml version="1.0" encoding="utf-8"?> - <layout xmlns:android="http://schemas.android.com/apk/res/android"> + <?xml version="1.0" encoding="utf-8"?> + <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> - <variable name="task" type="com.android.example.Task" /> - <variable name="presenter" type="com.android.example.Presenter" /> + <variable name="task" type="com.android.example.Task" /> + <variable name="presenter" type="com.android.example.Presenter" /> </data> - <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> - <Button android:layout_width="wrap_content" android:layout_height="wrap_content" - android:onClick="@{() -> presenter.onSaveClick(task)}" /> + <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> + <Button android:layout_width="wrap_content" android:layout_height="wrap_content" + android:onClick="@{() -> presenter.onSaveClick(task)}" /> </LinearLayout> </layout> </pre> @@ -465,7 +465,7 @@ public class Presenter { above could be written as: </p> <pre> - android:onClick="@{(view) -> presenter.onSaveClick(task)}" + android:onClick="@{(view) -> presenter.onSaveClick(task)}" </pre> Or if you wanted to use the parameter in the expression, it could work as follows: <pre> @@ -474,7 +474,7 @@ public class Presenter { } </pre> <pre> - android:onClick="@{(theView) -> presenter.onSaveClick(theView, task)}" + android:onClick="@{(theView) -> presenter.onSaveClick(theView, task)}" </pre> You can use a lambda expression with more than one parameter: <pre> @@ -483,8 +483,8 @@ public class Presenter { } </pre> <pre> - <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" - android:onCheckedChanged="@{(cb, isChecked) -> presenter.completeChanged(task, isChecked)}" /> + <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" + android:onCheckedChanged="@{(cb, isChecked) -> presenter.completeChanged(task, isChecked)}" /> </pre> <p> If the event you are listening to returns a value whose type is not {@code @@ -498,7 +498,7 @@ public class Presenter { } </pre> <pre> - android:onLongClick="@{(theView) -> presenter.onLongClick(theView, task)}" + android:onLongClick="@{(theView) -> presenter.onLongClick(theView, task)}" </pre> <p> If the expression cannot be evaluated due to {@code null} objects, Data Binding returns @@ -510,7 +510,7 @@ If you need to use an expression with a predicate (e.g. ternary), you can use {@code void} as a symbol. </p> <pre> - android:onClick="@{(v) -> v.isVisible() ? doSomething() : void}" + android:onClick="@{(v) -> v.isVisible() ? doSomething() : void}" </pre> <h5>Avoid Complex Listeners</h5> @@ -580,7 +580,7 @@ any business logic inside the callback method that you invoked from the listener </pre> <p> When there are class name conflicts, one of the classes may be renamed to an - “alias:” + "alias:" </p> <pre> @@ -601,7 +601,7 @@ any business logic inside the callback method that you invoked from the listener <import type="com.example.User"/> <import type="java.util.List"/> <variable name="user" type="User"/> - <variable name="userList" type="List&lt;User>"/> + <variable name="userList" type="List<User>"/> </data> </pre> <p class="caution"> @@ -695,7 +695,7 @@ any business logic inside the callback method that you invoked from the listener <p> By default, a Binding class is generated based on the name of the layout file, starting it with upper-case, removing underscores ( _ ) and - capitalizing the following letter and then suffixing “Binding”. This class + capitalizing the following letter and then suffixing "Binding". This class will be placed in a databinding package under the module package. For example, the layout file <code>contact_item.xml</code> will generate <code>ContactItemBinding</code>. If the module package is @@ -718,7 +718,7 @@ any business logic inside the callback method that you invoked from the listener This generates the binding class as <code>ContactItem</code> in the databinding package in the module package. If the class should be generated in a different package within the module package, it may be prefixed with - “.”: + ".": </p> <pre> @@ -741,7 +741,7 @@ any business logic inside the callback method that you invoked from the listener </h3> <p> - Variables may be passed into an included layout's binding from the + Variables may be passed into an included layout's binding from the containing layout by using the application namespace and the variable name in an attribute: </p> @@ -855,8 +855,8 @@ any business logic inside the callback method that you invoked from the listener <pre> android:text="@{String.valueOf(index + 1)}" -android:visibility="@{age &lt; 13 ? View.GONE : View.VISIBLE}" -android:transitionName='@{"image_" + id}' +android:visibility="@{age < 13 ? View.GONE : View.VISIBLE}" +android:transitionName='@{"image_" + id}' </pre> <h4 id="missing_operations"> Missing Operations @@ -945,9 +945,9 @@ android:transitionName='@{"image_" + id}' <import type="android.util.SparseArray"/> <import type="java.util.Map"/> <import type="java.util.List"/> - <variable name="list" type="List&lt;String>"/> - <variable name="sparse" type="SparseArray&lt;String>"/> - <variable name="map" type="Map&lt;String, String>"/> + <variable name="list" type="List<String>"/> + <variable name="sparse" type="SparseArray<String>"/> + <variable name="map" type="Map<String, String>"/> <variable name="index" type="int"/> <variable name="key" type="String"/> </data> @@ -969,17 +969,17 @@ android:text="@{map[key]}" </p> <pre> -android:text='@{map["firstName"]}' +android:text='@{map["firstName"]}' </pre> <p> It is also possible to use double quotes to surround the attribute value. - When doing so, String literals should either use the &quot; or back quote + When doing so, String literals should either use the ' or back quote (`). </p> <pre> android:text="@{map[`firstName`}" -android:text="@{map[&quot;firstName&quot;]}" +android:text="@{map['firstName']}" </pre> <h4 id="resources"> Resources @@ -1216,7 +1216,7 @@ private static class User { } </pre> <p> - That's it! To access the value, use the set and get accessor methods: + That's it! To access the value, use the set and get accessor methods: </p> <pre> @@ -1247,15 +1247,15 @@ user.put("age", 17); <pre> <data> <import type="android.databinding.ObservableMap"/> - <variable name="user" type="ObservableMap&lt;String, Object>"/> + <variable name="user" type="ObservableMap<String, Object>"/> </data> … <TextView - android:text='@{user["lastName"]}' + android:text='@{user["lastName"]}' android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView - android:text='@{String.valueOf(1 + (Integer)user["age"])}' + android:text='@{String.valueOf(1 + (Integer)user["age"])}' android:layout_width="wrap_content" android:layout_height="wrap_content"/> </pre> @@ -1277,15 +1277,15 @@ user.add(17); <data> <import type="android.databinding.ObservableList"/> <import type="com.example.my.app.Fields"/> - <variable name="user" type="ObservableList&lt;Object>"/> + <variable name="user" type="ObservableList<Object>"/> </data> … <TextView - android:text='@{user[Fields.LAST_NAME]}' + android:text='@{user[Fields.LAST_NAME]}' android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView - android:text='@{String.valueOf(1 + (Integer)user[Fields.AGE])}' + android:text='@{String.valueOf(1 + (Integer)user[Fields.AGE])}' android:layout_width="wrap_content" android:layout_height="wrap_content"/> </pre> @@ -1428,7 +1428,7 @@ public abstract void setNote(String note); <p> When inflating another layout, a binding must be established for the new - layout. Therefore, the <code>ViewStubProxy</code> must listen to the <code>ViewStub</code>'s + layout. Therefore, the <code>ViewStubProxy</code> must listen to the <code>ViewStub</code>'s {@link android.view.ViewStub.OnInflateListener} and establish the binding at that time. Since only one can exist, the <code>ViewStubProxy</code> allows the developer to set an <code>OnInflateListener</code> on it that it will call after establishing the binding. @@ -1443,9 +1443,9 @@ public abstract void setNote(String note); </h4> <p> - At times, the specific binding class won't be known. For example, a + At times, the specific binding class won't be known. For example, a {@link android.support.v7.widget.RecyclerView.Adapter} operating against arbitrary layouts - won't know the specific binding class. It still must assign the binding value during the + won't know the specific binding class. It still must assign the binding value during the {@link android.support.v7.widget.RecyclerView.Adapter#onBindViewHolder}. </p> @@ -1499,13 +1499,13 @@ public void onBindViewHolder(BindingHolder holder, int position) { For an attribute, data binding tries to find the method setAttribute. The namespace for the attribute does not matter, only the attribute name itself. <p> - For example, an expression associated with TextView's attribute + For example, an expression associated with TextView's attribute <strong><code>android:text</code></strong> will look for a setText(String). If the expression returns an int, data binding will search for a setText(int) method. Be careful to have the expression return the correct type, casting if necessary. Note that data binding will work even if no attribute exists with the given name. You can then easily "create" attributes for any setter by - using data binding. For example, support DrawerLayout doesn't have any + using data binding. For example, support DrawerLayout doesn't have any attributes, but plenty of setters. You can use the automatic setters to use one of these. </p> @@ -1522,7 +1522,7 @@ namespace for the attribute does not matter, only the attribute name itself. </h3> <p> - Some attributes have setters that don't match by name. For these + Some attributes have setters that don't match by name. For these methods, an attribute may be associated with the setter through {@link android.databinding.BindingMethods} annotation. This must be associated with a class and contains {@link android.databinding.BindingMethod} annotations, one for @@ -1591,8 +1591,8 @@ public static void loadImage(ImageView view, String url, Drawable error) { } </pre> <pre> -<ImageView app:imageUrl=“@{venue.imageUrl}” -app:error=“@{@drawable/venueError}”/> +<ImageView app:imageUrl="@{venue.imageUrl}" +app:error="@{@drawable/venueError}"/> </pre> <p> @@ -1747,7 +1747,7 @@ public static void setListener(View view, final OnViewDetachedFromWindow detach, <pre> <TextView - android:text='@{userMap["lastName"]}' + android:text='@{userMap["lastName"]}' android:layout_width="wrap_content" android:layout_height="wrap_content"/> </pre> diff --git a/docs/html/topic/libraries/support-library/features.jd b/docs/html/topic/libraries/support-library/features.jd index d648384399da..0f63bf669687 100755 --- a/docs/html/topic/libraries/support-library/features.jd +++ b/docs/html/topic/libraries/support-library/features.jd @@ -141,19 +141,13 @@ page.title=Support Library Features API reference. </p> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/v4/</code> directory. The library does not contain user -interface resources. To include it in your application project, follow the instructions for -<a href="{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without -resources</a>.</p> - <p class="caution"><strong>Caution:</strong> Using dynamic dependencies, especially for higher version numbers, can cause unexpected version updates and regression incompatibilities.</p> <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:support-v4:23.3.0 +com.android.support:support-v4:24.1.1 </pre> @@ -168,15 +162,6 @@ com.android.support:support-v4:23.3.0 </p> <p> - After you download the Android Support Libraries, this library is located in the - <code><sdk>/extras/android/support/multidex/</code> directory. The library does not contain - user interface resources. To include it in your application project, follow the instructions - for - <a href= "{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without - resources</a>. -</p> - -<p> The Gradle build script dependency identifier for this library is as follows: </p> @@ -228,16 +213,10 @@ com.android.support:multidex:1.0.0 </li> </ul> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/v7/appcompat/</code> directory. The library contains user -interface resources. To include it in your application project, follow the instructions for -<a href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries with -resources</a>.</p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:appcompat-v7:23.3.0 +com.android.support:appcompat-v7:24.1.1 </pre> @@ -249,16 +228,10 @@ widget, which lets you show information inside cards that have a consistent look on any app. These cards are useful for material design implementations, and are used extensively in layouts for TV apps.</p> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/v7/cardview/</code> directory. The library contains user interface -resources. To include it in your application project, follow the instructions -for <a href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding -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:23.3.0 +com.android.support:cardview-v7:24.1.1 </pre> @@ -271,16 +244,10 @@ allows you to arrange user interface elements using a grid of rectangular cells. For detailed information about the v7 gridlayout library APIs, see the {@link android.support.v7.widget android.support.v7.widget} package in the API reference.</p> -<p>This library is located in the <code><sdk>/extras/android/support/v7/gridlayout/</code> - directory . The library contains user - interface resources. To include it in your application project, follow the instructions for - <a href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries with - resources</a>.</p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:gridlayout-v7:23.3.0 +com.android.support:gridlayout-v7:24.1.1 </pre> @@ -300,21 +267,10 @@ information about the v7 mediarouter library APIs, see the {@link android.support.v7.media android.support.v7.media} package in the API reference.</p> -<p>The v7 mediarouter library is located in the -<code><sdk>/extras/android/support/v7/mediarouter/</code> directory after -you download the Android Support Library. It's provided as a library project -with a dependency on the v7 appcompat library, so you'll need to include both -libraries in your build path when setting up your project. For more information -on how to set up your project, follow the instructions in <a -href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries -with resources</a>.</p> - -<p>The Gradle builder script dependency identifier is as follows: -<code>com.android.support:support-v7-mediarouter:<revision></code>, -where "<revision>" is the minimum revision at which the library is available. For example:</p> +<p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:mediarouter-v7:23.3.0 +com.android.support:mediarouter-v7:24.1.1 </pre> <p class="caution">The v7 mediarouter library APIs introduced in Support Library @@ -331,16 +287,10 @@ prominent colors from an image. For example, a music app could use a from an album cover, and use those colors to build a color-coordinated song title card.</p> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/v7/palette/</code> directory. The library does not contain -user interface resources. To include it in your application project, follow the instructions for -<a href="{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without -resources</a>.</p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:palette-v7:23.3.0 +com.android.support:palette-v7:24.1.1 </pre> @@ -353,16 +303,10 @@ class. This class provides support for the widget, a view for efficiently displaying large data sets by providing a limited window of data items.</p> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/v7/recyclerview/</code> directory. The library contains -user interface resources. To include it in your application project, follow the instructions -for <a href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding -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:23.3.0 +com.android.support:recyclerview-v7:24.1.1 </pre> @@ -382,25 +326,12 @@ such as {@link android.support.v7.preference.CheckBoxPreference} and {@link android.support.v7.preference.ListPreference}. </p> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/v7/preference</code> directory. For more information -on how to set up your project, follow the instructions in <a -href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries -with resources</a>. </p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:preference-v7:23.3.0 +com.android.support:preference-v7:24.1.1 </pre> - - - - - - - <h2 id="v8">v8 Support Library</h2> <p>This library is designed to be used with Android 2.2 (API level 8) and higher. @@ -446,16 +377,10 @@ defaultConfig { android.support.v13} package in the API reference. </p> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/v13/</code> directory. The library does not contain user -interface resources. To include it in your application project, follow the instructions for -<a href="{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without -resources</a>.</p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:support-v13:23.3.0 +com.android.support:support-v13:24.1.1 </pre> @@ -478,16 +403,10 @@ for preference interfaces such as package in the API reference. </p> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/v14/</code> directory. The library does not contain user -interface resources. To include it in your application project, follow the instructions for -<a href="{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without -resources</a>.</p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:preference-v14:23.3.0 +com.android.support:preference-v14:24.1.1 </pre> @@ -507,16 +426,10 @@ interface and classes, such as package in the API reference. </p> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/v17/</code> directory. The library does not contain user -interface resources. To include it in your application project, follow the instructions for -<a href="{@docRoot}tools/support-library/setup.html#libs-without-res">Adding libraries without -resources</a>.</p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:preference-leanback-v17:23.3.0 +com.android.support:preference-leanback-v17:24.1.1 </pre> @@ -549,16 +462,10 @@ com.android.support:preference-leanback-v17:23.3.0 into a {@link android.support.v17.leanback.app.RowsFragment}.</li> </ul> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/v17/leanback</code> directory. For more information -on how to set up your project, follow the instructions in <a -href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries -with resources</a>. </p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:leanback-v17:23.3.0 +com.android.support:leanback-v17:24.1.1 </pre> @@ -570,16 +477,10 @@ package provides APIs to support adding annotation metadata to your apps. </p> <p></p> -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/annotations</code> directory. For more information -on how to set up your project, follow the instructions in <a -href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries -with resources</a>. </p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:support-annotations:23.3.0 +com.android.support:support-annotations:24.1.1 </pre> @@ -594,17 +495,10 @@ provides APIs to support adding material design components and patterns to your app developers to build upon, such as navigation drawers, floating action buttons (<i>FAB</i>), snackbars, and <a href="{@docRoot}design/building-blocks/tabs.html">tabs</a>. </p> - -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/design</code> directory. For more information -on how to set up your project, follow the instructions in <a -href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries -with resources</a>. </p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:design:23.3.0 +com.android.support:design:24.1.1 </pre> @@ -622,17 +516,10 @@ and <a href="{@docRoot}reference/android/support/customtabs/CustomTabsCallback.html">Custom Tabs Callback</a>. </p> - -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/customtabs</code> directory. For more information -on how to set up your project, follow the instructions in <a -href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries -with resources</a>. </p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:customtabs:23.3.0 +com.android.support:customtabs:24.1.1 </pre> @@ -653,17 +540,10 @@ and <a href="{@docRoot}reference/android/support/percent/PercentRelativeLayout.html"> PercentRelativeLayout</a>. </p> - -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/percent</code> directory. For more information -on how to set up your project, follow the instructions in <a -href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries -with resources</a>. </p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:percent:23.3.0 +com.android.support:percent:24.1.1 </pre> @@ -683,15 +563,8 @@ and <a href="{@docRoot}reference/android/support/app/recommendation/RecommendationExtender.html"> RecommendationExtender</a>. </p> - -<p>After you download the Android Support Libraries, this library is located in the -<code><sdk>/extras/android/support/recommendation</code> directory. For more information -on how to set up your project, follow the instructions in <a -href="{@docRoot}tools/support-library/setup.html#libs-with-res">Adding libraries -with resources</a>. </p> - <p>The Gradle build script dependency identifier for this library is as follows:</p> <pre> -com.android.support:recommendation:23.3.0 +com.android.support:recommendation:24.1.1 </pre> diff --git a/docs/html/topic/libraries/support-library/revisions.jd b/docs/html/topic/libraries/support-library/revisions.jd index 7e78925e9587..ef73d1dbe5d2 100644 --- a/docs/html/topic/libraries/support-library/revisions.jd +++ b/docs/html/topic/libraries/support-library/revisions.jd @@ -6,9 +6,34 @@ page.metaDescription=This page provides details about the Support Library packag <p>This page provides details about the Support Library package releases.</p> <div class="toggle-content opened"> - <p id="rev24-1-0"> + <p id="rev24-1-1"> <a href="#" onclick="return toggleContent(this)"><img src= "{@docRoot}assets/images/styles/disclosure_up.png" class= + "toggle-content-img" alt="">Android Support Library, revision 24.1.1</a> + <em>(July 2016)</em> + </p> + + <div class="toggle-content-toggleme"> + + <p>Fixed issues:</p> + + <ul> + <li>Fixes an issue in the 24.1.0 release which affected resource IDs + shared between support libraries. This issue caused apps that depended on + support libraries with resources (such as design and appcompat) to + encounter issues caused by resource ID mismatches. + </li> + </ul> + + </div> +</div> + +<!-- end of collapsible section: 24.1.1 --> + +<div class="toggle-content closed"> + <p id="rev24-1-0"> + <a href="#" onclick="return toggleContent(this)"><img src= + "{@docRoot}assets/images/styles/disclosure_down.png" class= "toggle-content-img" alt="">Android Support Library, revision 24.1.0</a> <em>(July 2016)</em> </p> diff --git a/docs/html/topic/libraries/support-library/setup.jd b/docs/html/topic/libraries/support-library/setup.jd index 62f7148acc7c..0cb9389ff508 100755 --- a/docs/html/topic/libraries/support-library/setup.jd +++ b/docs/html/topic/libraries/support-library/setup.jd @@ -10,18 +10,12 @@ page.title=Support Library Setup <ol> <li><a href="#download">Downloading the Support Library</a></li> <li><a href="#choosing">Choosing Support Libraries</a></li> - <li><a href="#add-library">Adding Support Libraries</a> - <ol> - <li><a href="#libs-without-res">Adding libraries without resources</a></li> - <li><a href="#libs-with-res">Adding libraries with resources</a></li> - </ol> - </li> + <li><a href="#add-library">Adding Support Libraries</a></li> <li><a href="#using-apis">Using Support Library APIs</a> <ol> <li><a href="#manifest">Manifest Declaration Changes</a></li> </ol> </li> - <li><a href="#samples">Code Samples</a></li> </ol> <h2>See also</h2> @@ -45,8 +39,8 @@ page.title=Support Library Setup <h2 id="download">Downloading the Support Libraries</h2> -<p>The Android Support Library package is provided as a supplemental download to the Android SDK - and is available through the Android +<p>The Android Support Repository package is provided as a supplemental download + to the Android SDK and is available through the Android <a href="{@docRoot}tools/help/sdk-manager.html">SDK Manager</a>. Follow the instructions below to obtain the Support Library files. </p> @@ -57,22 +51,18 @@ page.title=Support Library Setup <li>Start the Android <a href="{@docRoot}tools/help/sdk-manager.html">SDK Manager</a>.</li> <li>In the SDK Manager window, scroll to the end of the <em>Packages</em> list, find the <em>Extras</em> folder and, if necessary, expand to show its contents.</li> - <li>Select the <strong>Android Support Library</strong> item. - <p class="note"> - <strong>Note:</strong> If you're developing with Android Studio, select and install the - <strong>Android Support Repository</strong> item instead. - </p> - </li> + <li>Select the <strong>Android Support Repository</strong> item.</li> <li>Click the <strong>Install packages...</strong> button.</li> </ol> <img src="{@docRoot}images/tools/sdk-manager-support-libs.png" width="525" alt="" /> -<p class="img-caption"><strong>Figure 1.</strong> The Android SDK Manager with the -Android Support Library selected.</p> +<p class="img-caption"><strong>Figure 1.</strong> The Android SDK Manager with +Android Support Repository selected.</p> <p>After downloading, the tool installs the Support Library files to your existing Android SDK directory. The library files are located in the following subdirectory of your SDK: - {@code <sdk>/extras/android/support/} directory.</p> + <code><sdk>/extras/android/m2repository/com/android/support/</code> + directory.</p> <h2 id="choosing">Choosing Support Libraries</h2> @@ -89,20 +79,7 @@ Android Support Library selected.</p> classpath dependencies within your development environment. You must perform this procedure for each Support Library you want to use.</p> -<p>Some Support Libraries contain resources beyond compiled code classes, such as images or XML - files. For example, the <a href="{@docRoot}tools/support-library/features.html#v7-appcompat">v7 - appcompat</a> and <a href="{@docRoot}tools/support-library/features.html#v7-gridlayout">v7 - gridlayout</a> libraries include resources.</p> - -<p>If you are not sure if a library contains resources, check the - <a href="{@docRoot}tools/support-library/features.html">Support Library Features</a> page. - The following sections describe how to add a Support Library with or without resources to your - application project. </p> - - -<h3 id="libs-without-res">Adding libraries without resources</h3> - -<p>To add a Support Library without resources to your application project:</p> +<p>To add a Support Library to your application project:</p> <ol> <li>Make sure you have downloaded the <strong>Android Support Repository</strong> @@ -113,37 +90,12 @@ Android Support Library selected.</p> <pre> dependencies { ... - <b>compile "com.android.support:support-v4:18.0.+"</b> -} -</pre> - </li> - </ol> - - -<h3 id="libs-with-res">Adding libraries with resources</h3> - -<p>To add a Support Library with resources (such as - <a href="{@docRoot}tools/support-library/features.html#v7-appcompat">v7 - appcompat</a> for action bar) to your application project:</p> - - <ol> - <li>Make sure you have downloaded the <strong>Android Support Repository</strong> - using the <a href="#download">SDK Manager</a>.</li> - <li>Open the {@code build.gradle} file for your application.</li> - <li>Add the support library feature project identifier to the {@code dependencies} section. - For example, to include the {@code appcompat} project add - {@code compile "com.android.support:appcompat-v7:18.0.+"} to the dependencies section, as - shown in the following example: -<pre> -dependencies { - ... - <b>compile "com.android.support:appcompat-v7:18.0.+"</b> + <b>compile "com.android.support:support-v4:24.1.1"</b> } </pre> </li> </ol> - <h2 id="using-apis">Using Support Library APIs</h2> <p>Support Library classes that provide support for existing framework APIs typically have the @@ -224,18 +176,3 @@ android { <code>"4"</code>). The highest support library level you include in your application determines the lowest API version in which it can operate. </p> - - -<h2 id="samples">Code Samples</h2> - -<p>Each Support Library includes code samples to help you get started using the support -APIs. The code is included in the download from the SDK Manager and is placed inside the Android -SDK installation directory, as listed below:</p> - -<ul> - <li>4v Samples: {@code <sdk>/extras/android/support/samples/Support4Demos/}</li> - <li>7v Samples: {@code <sdk>/extras/android/support/samples/Support7Demos/}</li> - <li>13v Samples: {@code <sdk>/extras/android/support/samples/Support13Demos/}</li> - <li>App Navigation: {@code <sdk>/extras/android/support/samples/SupportAppNavigation/}</li> -</ul> - diff --git a/docs/html/topic/performance/performance_toc.cs b/docs/html/topic/performance/performance_toc.cs index 49191bcd85b5..8c395239872a 100644 --- a/docs/html/topic/performance/performance_toc.cs +++ b/docs/html/topic/performance/performance_toc.cs @@ -656,7 +656,7 @@ description= "How to sync and back up app and user data to remote web services in the cloud and how to restore the data back to multiple devices." - >Syncing to the Cloud</a> + >Backing up App Data to the Cloud</a> </div> <ul> <li><a href="<?cs var:toroot ?>training/backup/autosyncapi.html"> diff --git a/docs/html/training/_book.yaml b/docs/html/training/_book.yaml index 00f9295b05f7..d70958668153 100644 --- a/docs/html/training/_book.yaml +++ b/docs/html/training/_book.yaml @@ -436,7 +436,7 @@ toc: path: /training/efficient-downloads/redundant_redundant.html - title: Modifying Patterns Based on the Connectivity Type path: /training/efficient-downloads/connectivity_patterns.html - - title: Syncing to the Cloud + - title: Backing up App Data to the Cloud path: /training/backup/index.html path_attributes: - name: description @@ -1373,6 +1373,11 @@ toc: path_attributes: - name: description value: How to use the SafetyNet service to analyze a device where your app is running and get information about its compatibility with your app. + - title: Checking URLs with the Safe Browsing API + path: /training/safebrowsing/index.html + path_attributes: + - name: description + value: How to use the SafetyNet service to determine if a URL is designated as a known threat. - title: Enhancing Security with Device Management Policies path: /work/device-management-policy.html path_attributes: diff --git a/docs/html/training/backup/backupapi.jd b/docs/html/training/backup/backupapi.jd index b115b8b21455..2f3e93943f37 100644 --- a/docs/html/training/backup/backupapi.jd +++ b/docs/html/training/backup/backupapi.jd @@ -1,5 +1,5 @@ page.title=Using the Backup API -parent.title=Syncing to the Cloud +parent.title=Backing up App Data to the Cloud parent.link=index.html trainingnavtop=true diff --git a/docs/html/training/basics/firstapp/building-ui.jd b/docs/html/training/basics/firstapp/building-ui.jd index 275500c88141..a680c733f99e 100644 --- a/docs/html/training/basics/firstapp/building-ui.jd +++ b/docs/html/training/basics/firstapp/building-ui.jd @@ -71,38 +71,31 @@ android.view.View} objects.</p> <h2 id="LinearLayout">Create a Linear Layout</h2> <ol> -<li>In Android Studio, from the <code>res/layout</code> directory, open the {@code content_my.xml} -file. -<p>The BlankActivity template you chose when you created this project includes the -<code>content_my.xml</code> file with a {@link android.widget.RelativeLayout} root view and a -{@link android.widget.TextView} child view.</p> -</li> -<li>In the <strong>Preview</strong> pane, click the Hide icon <img src="{@docRoot}images/tools/as-hide-side.png" - style="vertical-align:baseline;margin:0; max-height:1.5em" /> to close the Preview pane. - <p> In Android Studio, when you open a layout file, you’re first shown - the Preview pane. Clicking elements in this pane opens the WYSIWYG tools in the Design pane. For - this lesson, you’re going to work directly with the XML.</p></li> -<li>Delete the {@link android.widget.TextView <TextView>} element.</li> -<li>Change the {@link android.widget.RelativeLayout <RelativeLayout>} element to -{@link android.widget.LinearLayout <LinearLayout>}.</li> -<li>Add the <a href="{@docRoot}reference/android/widget/LinearLayout.html#attr_android:orientation"> -{@code android:orientation}</a> attribute and set it to <code>"horizontal"</code>.</li> -<li>Remove the {@code android:padding} attributes and the {@code tools:context} attribute. -</ol> - -<p>The result looks like this:</p> - -<pre> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" + <li>From the <code>res/layout/</code> directory, open the + <code>activity_main.xml</code> file. + <p>This XML file defines the layout of your activity. It contains the + default "Hello World" text view.</p> + </li> + <li>When you open a layout file, you’re first shown the design editor in the + <a href="/studio/write/layout-editor.html">Layout Editor</a>. For this lesson, + you work directly with the XML, so click the <b>Text</b> tab to switch to + the text editor. + </li> + <li>Replace the contents of the file with the following XML: + <pre><?xml version="1.0" encoding="utf-8"?> +<LinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" - android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" - app:layout_behavior="@string/appbar_scrolling_view_behavior" - tools:showIn="@layout/activity_my"> + android:orientation="horizontal"> +</LinearLayout> </pre> + </li> + +</ol> + <p>{@link android.widget.LinearLayout} is a view group (a subclass of {@link android.view.ViewGroup}) that lays out child views in either a vertical or horizontal orientation, as specified by the <a @@ -128,29 +121,25 @@ href="{@docRoot}guide/topics/ui/declaring-layout.html">Layout</a> guide.</p> <h2 id="TextInput">Add a Text Field</h2> -<p>As with every {@link android.view.View} object, you must define certain XML attributes to specify -the {@link android.widget.EditText} object's properties.</p> - -<ol> -<li>In the <code>content_my.xml</code> file, within the -{@link android.widget.LinearLayout <LinearLayout>} element, define an -{@link android.widget.EditText <EditText>} element with the <code>id</code> attribute -set to <code>@+id/edit_message</code>.</li> -<li>Define the <code>layout_width</code> and <code>layout_height</code> attributes as -<code>wrap_content</code>.</li> -<li>Define a <code>hint</code> attribute as a string object named <code>edit_message</code>.</li> -</ol> - -<p>The {@link android.widget.EditText <EditText>} element should read as follows:</p> +<p>In the <code>activity_main.xml</code> file, within the +{@link android.widget.LinearLayout <LinearLayout>} element, add the following +{@link android.widget.EditText <EditText>} element:</p> -<pre> -<EditText android:id="@+id/edit_message" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:hint="@string/edit_message" /> +<pre><LinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="horizontal"> + <b><EditText android:id="@+id/edit_message" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:hint="@string/edit_message" /></b> +</LinearLayout> </pre> -<p>Here are the {@link android.widget.EditText <EditText>} attributes you added:</p> +<p>Here is a description of the attributes in the + {@link android.widget.EditText <EditText>} you added:</p> <dl> <dt><a href="{@docRoot}reference/android/view/View.html#attr_android:id">{@code android:id}</a></dt> @@ -222,29 +211,20 @@ the same name does not cause collisions.</p> <h2 id="Strings">Add String Resources</h2> <p>By default, your Android project includes a string resource file at -<code>res/values/strings.xml</code>. Here, you'll add a new string named -<code>"edit_message"</code> and set the value to "Enter a message."</p> +<code>res/values/strings.xml</code>. Here, you'll add two new strings.</p> <ol> -<li>In Android Studio, from the <code>res/values</code> directory, open <code>strings.xml</code>.</li> -<li>Add a line for a string named <code>"edit_message"</code> with the value, "Enter a message". -</li> -<li>Add a line for a string named <code>"button_send"</code> with the value, "Send". -<p>You'll create the button that uses this string in the next section.</p> -</li> -</ol> - -<p>The result for <code>strings.xml</code> looks like this:</p> - -<pre> -<?xml version="1.0" encoding="utf-8"?> +<li>From the <code>res/values/</code> directory, open <code>strings.xml</code>.</li> +<li>Add two strings so that your file looks like this: +<pre><?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">My First App</string> - <string name="edit_message">Enter a message</string> - <string name="button_send">Send</string> - <string name="action_settings">Settings</string> + <b><string name="edit_message">Enter a message</string> + <string name="button_send">Send</string></b> </resources> </pre> +</li> +</ol> <p>For text in the user interface, always specify each string as a resource. String resources allow you to manage all UI text in a single location, @@ -260,40 +240,22 @@ class.</p> <h2 id="Button">Add a Button</h2> -<ol> -<li>In Android Studio, from the <code>res/layout</code> directory, edit the <code>content_my.xml</code> -file.</li> -<li>Within the -{@link android.widget.LinearLayout <LinearLayout>} element, define a -{@link android.widget.Button <Button>} element immediately following the -{@link android.widget.EditText <EditText>} element.</li> -<li>Set the button's width and height attributes to <code>"wrap_content"</code> so -the button is only as big as necessary to fit the button's text label.</li> -<li>Define the button's text label with the <a -href="{@docRoot}reference/android/widget/TextView.html#attr_android:text">{@code -android:text}</a> attribute; set its value to the <code>button_send</code> string -resource you defined in the previous section.</li> -</ol> - -<p>Your {@link android.widget.LinearLayout <LinearLayout>} should look like this:</p> - -<pre> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" +<p>Go back to the <code>activity_main.xml</code> file and add a button after the + {@link android.widget.EditText <EditText>}. Your file should look like this:</p> +<pre><LinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="horizontal" android:layout_width="match_parent" - android:layout_height="match_parent" - app:layout_behavior="@string/appbar_scrolling_view_behavior" - tools:showIn="@layout/activity_my"> + android:layout_height="match_parent"> <EditText android:id="@+id/edit_message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/edit_message" /> - <Button + <b><Button android:layout_width="wrap_content" android:layout_height="wrap_content" - android:text="@string/button_send" /> + android:text="@string/button_send" /></b> </LinearLayout> </pre> @@ -302,7 +264,7 @@ resource you defined in the previous section.</li> attribute, because it won't be referenced from the activity code.</p> <p>The layout is currently designed so that both the {@link android.widget.EditText} and {@link -android.widget.Button} widgets are only as big as necessary to fit their content, as Figure 2 shows. +android.widget.Button} widgets are only as big as necessary to fit their content, as figure 2 shows. </p> <img src="{@docRoot}images/training/firstapp/edittext_wrap.png" /> @@ -334,53 +296,36 @@ given the space they require.</p> <h2 id="Weight">Make the Input Box Fill in the Screen Width</h2> -<p>To fill the remaining space in your layout with the {@link android.widget.EditText} element, do -the following:</p> - -<ol> -<li>In the <code>content_my.xml</code> file, assign the -{@link android.widget.EditText <EditText>} element's <code>layout_weight</code> attribute a value -of <code>1</code>.</li> -<li>Also, assign {@link android.widget.EditText <EditText>} element's <code>layout_width</code> -attribute a value of <code>0dp</code>. +<p>In <code>activity_main.xml</code>, modify the + {@link android.widget.EditText <EditText>} so that the attributes look like + this:</p> <pre> -<EditText - android:layout_weight="1" - android:layout_width="0dp" - ... /> +<EditText android:id="@+id/edit_message" + <b>android:layout_weight="1" + android:layout_width="0dp"</b> + android:layout_height="wrap_content" + android:hint="@string/edit_message" /> </pre> -<p>To improve the layout efficiency when you specify the weight, you should change the -width of the {@link android.widget.EditText} to be -zero (0dp). Setting the width to zero improves layout performance because using +<p>Setting the width to zero (0dp) improves layout performance because using <code>"wrap_content"</code> as the width requires the system to calculate a width that is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space.</p> -<p>Figure 3 -shows the result when you assign all weight to the {@link android.widget.EditText} element.</p> - <img src="{@docRoot}images/training/firstapp/edittext_gravity.png" /> <p class="img-caption"><strong>Figure 3.</strong> The {@link android.widget.EditText} widget is given all the layout weight, so it fills the remaining space in the {@link android.widget.LinearLayout}.</p> -</li> -</ol> - -<p>Here’s how your complete <code>content_my.xml</code>layout file should now look:</p> +<p>Here’s how your complete <code>activity_main.xml</code>layout file should now look:</p> -<pre> -<?xml version="1.0" encoding="utf-8"?> +<pre><?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:orientation="horizontal" android:layout_width="match_parent" - android:layout_height="match_parent" - app:layout_behavior="@string/appbar_scrolling_view_behavior" - tools:showIn="@layout/activity_my"> + android:layout_height="match_parent"> <EditText android:id="@+id/edit_message" android:layout_weight="1" android:layout_width="0dp" @@ -406,7 +351,4 @@ that the SDK tools generated when you created the project.</p> <p>Continue to the <a href="starting-activity.html">next lesson</a> to learn how to respond to button presses, read content -from the text field, start another activity, and more.</p> - - - +from the text field, start another activity, and more.</p>
\ No newline at end of file diff --git a/docs/html/training/basics/firstapp/creating-project.jd b/docs/html/training/basics/firstapp/creating-project.jd index 4c2155b36314..cad32bf077d8 100644 --- a/docs/html/training/basics/firstapp/creating-project.jd +++ b/docs/html/training/basics/firstapp/creating-project.jd @@ -14,36 +14,19 @@ next.link=running-app.html <div id="tb-wrapper"> <div id="tb"> -<h2>This lesson teaches you to</h2> - -<ol> - <li><a href="#Studio">Create a Project with Android Studio</a></li> -</ol> - <h2>You should also read</h2> <ul> - <li><a href="{@docRoot}tools/projects/index.html">Managing Projects</a></li> + <li><a href="{@docRoot}studio/projects/index.html">Projects Overview</a></li> </ul> </div> </div> -<p>An Android project contains all the files that comprise the source code for your Android -app.</p> - -<p>This lesson -shows how to create a new project either using Android Studio or using the -SDK tools from a command line.</p> - -<p class="note"><strong>Note:</strong> You should already have Android Studio or the Android SDK -command-line tools installed. If not, <a -href="{@docRoot}studio/index.html">download them</a> before you start this -lesson.</p> - - -<h2 id="Studio">Create a Project with Android Studio</h2> +<p>This lesson shows you how to create a new Android project with + <a href="{@docRoot}studio/index.html">Android Studio</a> and describes some + of the files in the project.</p> <ol> <li>In Android Studio, create a new project: @@ -54,11 +37,12 @@ lesson.</p> Project</strong>. The <em>Create New Project</em> screen appears.</li> </ul> </li> - <li>Fill out the fields on the screen, and click <strong>Next</strong>. - <p>It is easier to follow these lessons if you use the same values as shown.</p> + <li>Fill out the fields on the screen. For <strong>Application Name</strong> + use "My First App". For <strong>Company Domain</strong>, use "example.com". + For the other fields, use the default values and click <strong>Next</strong> + <p>Here's a brief explanation of each field:</p> <ul> - <li><strong>Application Name</strong> is the app name that appears to users. - For this project, use "My First App."</li> + <li><strong>Application Name</strong> is the app name that appears to users.</li> <li><strong>Company domain</strong> provides a qualifier that will be appended to the package name; Android Studio will remember this qualifier for each new project you create.</li> <li><strong>Package name</strong> is the fully qualified name for the project (following the @@ -70,9 +54,8 @@ lesson.</p> files.</li> </ul> </li> - <li>Under <strong>Select the form factors your app will run on</strong>, check the box for <strong> - Phone and Tablet</strong>.</li> - <li>For <strong>Minimum SDK</strong>, select <strong>API 8: Android 2.2 (Froyo)</strong>. + <li>Under <strong>Target Android Devices</strong>, accept the default values + and click <strong>Next</strong>. <p>The Minimum Required SDK is the earliest version of Android that your app supports, indicated using the <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels"> API level</a>. To support as many devices as possible, you should set this to the lowest @@ -80,8 +63,13 @@ lesson.</p> app is possible only on newer versions of Android and it's not critical to the app's core feature set, you can enable the feature only when running on the versions that support it (as discussed in <a href="{@docRoot}training/basics/supporting-devices/platforms.html"> - Supporting Different Platform Versions</a>).</p></li> - <li>Leave all of the other options (TV, Wear, and Glass) unchecked and click <strong>Next.</strong></li> + Supporting Different Platform Versions</a>).</p> + </li> + + <li>Under <strong>Add an Activity to Mobile</strong>, select <strong>Empty + Activity</strong> and click <strong>Next</strong>. + </li> + <div class="sidebox-wrapper"> <div class="sidebox"> <h3>Activities</h3> @@ -93,43 +81,25 @@ lesson.</p> Activities</a> for more information.</p> </div> </div> - <li>Under <strong>Add an activity to <<em>template</em>></strong>, - select <strong>Basic Activity</strong> and click <strong>Next</strong>. - </li> - - <li>Under <strong>Customize the Activity</strong>, change the - <strong>Activity Name</strong> to <em>MyActivity</em>. The <strong>Layout - Name</strong> changes to <em>activity_my</em>, and the <strong>Title</strong> - to <em>MyActivity</em>. The <strong>Menu Resource Name</strong> is - <em>menu_my</em>. - </li> - <li>Click the <strong>Finish</strong> button to create the project. - </li> + <li>Under <strong>Customize the Activity</strong>, accept the default values + and click <strong>Finish</strong>. </ol> <p>Your Android project is now a basic "Hello World" app that contains some default files. Take a moment to review the most important of these:</p> <dl> - <dt><code>app/src/main/res/layout/activity_my.xml</code></dt> - <dd>This XML layout file is for the activity you added when you created the project - with Android Studio. Following the New Project workflow, Android Studio presents this file - with both a text - view and a preview of the screen UI. The file contains some default interface elements - from the material design library, including the - <a href="{@docRoot}training/appbar/index.html">app bar</a> and a floating action button. - It also includes a separate layout file with the main content.</dd> - - <dt><code>app/src/main/res/layout/content_my.xml</code></dt> - <dd>This XML layout file resides in {@code activity_my.xml}, and contains some settings and - a {@code TextView} element that displays the message, "Hello world!".</dd> - - <dt><code>app/src/main/java/com.mycompany.myfirstapp/MyActivity.java</code></dt> - <dd>A tab for this file appears in Android Studio when the New Project workflow finishes. When you - select the file you see the class definition for the activity you created. When you build and - run the app, the {@link android.app.Activity} class starts the activity and loads the layout file - that says "Hello World!"</dd> + <dt><code>app/src/main/java/com.example.myfirstapp/MainActivity.java</code></dt> + <dd>This file appears in Android Studio after the New Project wizard finishes. + It contains the class definition for the activity you created earlier. When you build + and run the app, the {@link android.app.Activity} starts and loads the + layout file that says "Hello World!"</dd> + + <dt><code>app/src/main/res/layout/activity_main.xml</code></dt> + <dd>This XML file defines the layout of the activity. It contains a {@code TextView} + element with the text "Hello world!".</dd> + <dt><code>app/src/main/AndroidManifest.xml</code></dt> <dd>The <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest file</a> describes the fundamental characteristics of the app and defines each of its components. You'll revisit @@ -143,15 +113,15 @@ moment to review the most important of these:</p> <ul> <li><code>compiledSdkVersion</code> is the platform version against which you will compile your app. By default, this is set to the latest version of Android available in your SDK. - (It should be Android 4.1 or greater; if you don't have such a version available, you must - install one using the <a href="{@docRoot}studio/intro/update.html">SDK Manager</a>.) + By default, this is set to the latest version of Android SDK installed on your + development machine. You can still build your app to support older versions, but setting this to the latest version allows you to enable new features and optimize your app for a great user experience on the latest devices.</li> <li><code>applicationId</code> is the fully qualified package name for your application that - you specified during the New Project workflow.</li> + you specified in the New Project wizard.</li> <li><code>minSdkVersion</code> is the Minimum SDK version you specified during the New Project - workflow. This is the earliest version of the Android SDK that your app supports.</li> + wizard. This is the earliest version of the Android SDK that your app supports.</li> <li><code>targetSdkVersion</code> indicates the highest version of Android with which you have tested your application. As new versions of Android become available, you should test your app on the new version and update this value to match the latest API level and @@ -172,8 +142,8 @@ moment to review the most important of these:</p> for various <a href="{@docRoot}training/multiscreen/screendensities.html">densities</a>. </dd> <dt><code>layout/</code></dt> - <dd>Directory for files that define your app's user interface like {@code activity_my.xml}, - discussed above, which describes a basic layout for the {@code MyActivity} + <dd>Directory for files that define your app's user interface like {@code activity_main.xml}, + discussed above, which describes a basic layout for the {@code MainActivity} class.</dd> <dt><code>menu/</code></dt> <dd>Directory for files that define your app's menu items.</dd> diff --git a/docs/html/training/basics/firstapp/index.jd b/docs/html/training/basics/firstapp/index.jd index cb5073f95c01..48b7190b73c0 100644 --- a/docs/html/training/basics/firstapp/index.jd +++ b/docs/html/training/basics/firstapp/index.jd @@ -23,25 +23,10 @@ helpoutsWidget=true <p>Welcome to Android application development!</p> -<p>This class teaches you how to build your first Android app. You’ll learn how to create an Android -project and run a debuggable version of the app. You'll also learn some fundamentals of Android app -design, including how to build a simple user interface and handle user input.</p> - -<h2>Set Up Your Environment</h2> - -<p>Before you start this class, be sure you have your development environment set up. You need -to:</p> -<ol> - <li>Download <a href="{@docRoot}studio/index.html">Android Studio</a>.</li> - <li>Download the latest SDK tools and platforms using the - <a href="{@docRoot}tools/help/sdk-manager.html">SDK Manager</a>.</li> -</ol> - -<p class="note"><strong>Note:</strong> Although most of this training class -expects that you're using Android Studio, some procedures include alternative -instructions for using -the SDK tools from the command line instead.</p> - -<p>This class uses a tutorial format to create a small Android app that teaches -you some fundamental concepts about Android development, so it's important that you follow each -step.</p> +<p>This class teaches you how to build your first Android app. You’ll learn how + to create an Android project with Android Studio and run a debuggable version + of the app. You'll also learn some fundamentals of Android app design, + including how to build a simple user interface and handle user input.</p> + +<p>Before you start this class, download and install + <a href="{@docRoot}studio/index.html">Android Studio</a>.</p>
\ No newline at end of file diff --git a/docs/html/training/basics/firstapp/running-app.jd b/docs/html/training/basics/firstapp/running-app.jd index 21fb64d83798..e8098711b9a9 100755 --- a/docs/html/training/basics/firstapp/running-app.jd +++ b/docs/html/training/basics/firstapp/running-app.jd @@ -26,7 +26,6 @@ helpoutsWidget=true <ul> <li><a href="{@docRoot}tools/device.html">Using Hardware Devices</a></li> <li><a href="{@docRoot}tools/devices/managing-avds.html">Managing AVDs with AVD Manager</a></li> - <li><a href="{@docRoot}tools/projects/index.html">Managing Projects</a></li> </ul> @@ -34,27 +33,20 @@ helpoutsWidget=true </div> -<p>If you followed the <a href="creating-project.html">previous lesson</a> to create an -Android project, it includes a default set of "Hello World" source files that allow you to -immediately run the app.</p> - -<p>How you run your app depends on two things: whether you have a real device running Android and -whether you're using Android Studio. This lesson shows you how to install and run your app on a -real device and on the Android emulator, and in both cases with either Android Studio or the command -line tools.</p> +<p>In the <a href="creating-project.html">previous lesson</a>, you created an + Android project. The project contains a default app that displays + "Hello World". In this lesson, you will run the app on a device or emulator.</p> <h2 id="RealDevice">Run on a Real Device</h2> -<p>If you have a device running Android, here's how to install and run your app.</p> - -<h3>Set up your device</h3> +<p>Set up your device as follows:</p> <ol> - <li>Plug in your device to your development machine with a USB cable. + <li>Connect your device to your development machine with a USB cable. If you're developing on Windows, you might need to install the appropriate USB driver for your - device. For help installing drivers, see the <a href="{@docRoot}tools/extras/oem-usb.html">OEM + device. For help installing drivers, see the <a href="{@docRoot}studio/run/oem-usb.html">OEM USB Drivers</a> document.</li> - <li>Enable <strong>USB debugging</strong> on your device. On Android 4.0 and newer, go to + <li>Enable <strong>USB debugging</strong> on your device by going to <strong>Settings > Developer options</strong>. <p class="note"><strong>Note:</strong> On Android 4.2 and newer, <strong>Developer options</strong> is hidden by default. To make it available, go @@ -63,73 +55,61 @@ line tools.</p> </li> </ol> -<h3>Run the app from Android Studio</h3> +<p>Run the app from Android Studio as follows:</p> + <ol> - <li>Select one of your project's files and click -<strong>Run</strong> <img -src="{@docRoot}images/tools/as-run.png" style="vertical-align:baseline;margin:0; max-height:1em" /> -from the toolbar.</li> - <li>In the <strong>Choose Device</strong> window that appears, select the - <strong>Choose a running device</strong> radio button, select your device, and click <strong>OK - </strong>.</li> + <li>In Android Studio, select your project and click + <strong>Run</strong> <img src="{@docRoot}images/tools/as-run.png" + style="vertical-align:baseline;margin:0; max-height:1em" /> + from the toolbar.</li> + <li>In the <strong>Select Deployment Target</strong> window, + select your device, and click <strong>OK</strong>.</li> </ol> <p>Android Studio installs the app on your connected device and starts it.</p> <h2 id="Emulator">Run on the Emulator</h2> -<p>Whether you're using Android Studio or the command line, to run your app on the emulator you need -to first create an <a href="{@docRoot}tools/devices/index.html">Android Virtual Device</a> (AVD). An -AVD is a device configuration for the Android emulator that allows you to model a specific -device.</p> - +<p>Before you run your app on an emulator, you need to create an + <a href="{@docRoot}tools/devices/index.html">Android Virtual Device</a> (AVD) + definition. An AVD definition defines the characteristics of an Android phone, + tablet, Android Wear, or Android TV device that you want to simulate in the + Android Emulator.</p> -<h3>Create an AVD</h3> +<p>Create an AVD Definition as follows:</p> <ol> - <li>Launch the Android Virtual Device Manager: - <ul> - <li>In Android Studio, select <strong>Tools > Android > AVD Manager</strong>, or click - the AVD Manager icon <img src="{@docRoot}images/tools/avd-manager-studio.png" - style="vertical-align:bottom;margin:0;height:19px"> in the toolbar. The - <em>AVD Manager</em> screen appears.</li> - <li>Or, from the command line, change directories to - <code>sdk/</code> and execute: - <pre class="no-pretty-print">tools/android avd</pre> - <p class="note"><strong>Note:</strong> The AVD Manager that appears - when launched from the command line is different from the version in - Android Studio, so the following instructions may not all apply.</p> - </li> - </ul> - - </li> + <li>Launch the Android Virtual Device Manager by selecting + <strong>Tools > Android > AVD Manager</strong>, or by clicking + the AVD Manager icon <img src="{@docRoot}images/tools/avd-manager-studio.png" + style="vertical-align:bottom;margin:0;height:19px"> in the toolbar.</li> <li>On the AVD Manager main screen, click <strong>Create Virtual Device</strong>.</li> - <li>In the Select Hardware window, select a device configuration, such as Nexus 6, - then click <strong>Next</strong>. + <li>In the Select Hardware page, select a phone device, such as Nexus 6, + then click <strong>Next</strong>. </li> - <li>Select the desired system version for the AVD and click <strong>Next</strong>. + <li>In the Select Image page, choose the desired system image for the AVD and + click <strong>Next</strong>. </li> - <li>Verify the configuration settings, then click <strong>Finish</strong>. + <li>Verify the configuration settings (for your first AVD, leave all the + settings as they are), and then click <strong>Finish</strong>. </li> </ol> <p>For more information about using AVDs, see -<a href="{@docRoot}tools/devices/managing-avds.html">Managing AVDs with AVD Manager</a>.</p> +<a href="{@docRoot}studio/run/managing-avds.html">Create and Manage Virtual Devices</a>.</p> -<h3>Run the app from Android Studio</h3> +<p>Run the app from Android Studio as follows:</p> <ol> - <li>In <strong>Android Studio</strong>, select your project and click <strong>Run</strong> - <img src="{@docRoot}images/tools/as-run.png" style="vertical-align:baseline;margin:0; max-height:1em" /> from the toolbar.</li> - <li>In the <strong>Choose Device</strong> window, click the <strong>Launch emulator</strong> radio - button.</li> - <li>From the <strong>Android virtual device</strong> pull-down menu, select the emulator - you created, and click <strong>OK</strong>.</li> + <li>In <strong>Android Studio</strong>, select your project and click + <strong>Run</strong> <img src="{@docRoot}images/tools/as-run.png" + style="vertical-align:baseline;margin:0; max-height:1em" /> + from the toolbar.</li> + <li>In the <strong>Select Deployment Target</strong> window, + select your emulator and click <strong>OK</strong>.</li> </ol> -<p>It can take a few minutes for the emulator to load itself. You may have to unlock the screen. +<p>It can take a few minutes for the emulator to start. You may have to unlock the screen. When you do, <em>My First App</em> appears on the emulator screen.</p> <p>That's how you build and run your Android app on the emulator! To start developing, continue to the <a href="building-ui.html">next -lesson</a>.</p> - - +lesson</a>.</p>
\ No newline at end of file diff --git a/docs/html/training/basics/firstapp/starting-activity.jd b/docs/html/training/basics/firstapp/starting-activity.jd index e84e17e5d867..ebf42cbe0438 100644 --- a/docs/html/training/basics/firstapp/starting-activity.jd +++ b/docs/html/training/basics/firstapp/starting-activity.jd @@ -19,9 +19,7 @@ helpoutsWidget=true <ol> <li><a href="#RespondToButton">Respond to the Send Button</a></li> <li><a href="#BuildIntent">Build an Intent</a></li> - <!-- <li><a href="#StartActivity">Start the Second Activity</a></li> --> <li><a href="#CreateActivity">Create the Second Activity</a></li> - <li><a href="#ReceiveIntent">Receive the Intent</a></li> <li><a href="#DisplayMessage">Display the Message</a></li> </ol> @@ -33,479 +31,202 @@ helpoutsWidget=true <p>After completing the <a href="building-ui.html">previous lesson</a>, you have an app that shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some -code to <code>MyActivity</code> that +code to <code>MainActivity</code> that starts a new activity when the user clicks the Send button.</p> <h2 id="RespondToButton">Respond to the Send Button</h2> <ol> -<li>In Android Studio, from the <code>res/layout</code> directory, edit the <code>content_my.xml</code> -file.</li> -<li>Add the <a -href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a> -attribute to the {@link android.widget.Button <Button>} element. - -<p class="code-caption">res/layout/content_my.xml</p> -<pre> -<Button - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/button_send" - android:onClick="sendMessage" /> -</pre> - -<p>The <a -href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code -android:onClick}</a> attribute’s value, <code>"sendMessage"</code>, is the name of a method in your -activity that the system calls when the user clicks the button.</p> -</li> -<li>In the <code>java/com.mycompany.myfirstapp</code> directory, open the <code>MyActivity.java</code> file.</li> -<li>Within the <code>MyActivity</code> class, add the {@code sendMessage()} method stub shown -below. - -<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p> -<pre> -/** Called when the user clicks the Send button */ -public void sendMessage(View view) { - // Do something in response to button -} -</pre> - -<p>In order for the system to match this method to the method name given to <a -href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a>, -the signature must be exactly as shown. Specifically, the method must:</p> - -<ul> -<li>Be public</li> -<li>Have a void return value</li> -<li>Have a {@link android.view.View} as the only parameter (this will be the {@link -android.view.View} that was clicked)</li> -</ul> - -</li> -</ol> - -<p>Next, you’ll fill in this method to read the contents of the text field and deliver that text to -another activity.</p> - -<h2 id="BuildIntent">Build an Intent</h2> - -<ol> -<li>In <code>MyActivity.java</code>, inside the {@code sendMessage()} method, create an -{@link android.content.Intent} to start an activity called {@code DisplayMessageActivity} with the -following code: - -<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p> -<pre> -public void sendMessage(View view) { - Intent intent = new Intent(this, DisplayMessageActivity.class); -} -</pre> - -<div class="sidebox-wrapper"> -<div class="sidebox"> -<h3>Intents</h3> -<p>An {@link android.content.Intent} is an object that provides runtime binding between separate -components (such as two activities). The {@link android.content.Intent} represents an -app’s "intent to do something." You can use intents for a wide -variety of tasks, but most often they’re used to start another activity. For more information, see -<a href="{@docRoot}guide/components/intents-filters.html ">Intents and Intent Filters</a>.</p> -</div> -</div> - -<p class="note"><strong>Note:</strong> The reference to {@code DisplayMessageActivity} -will raise an error if you’re using an IDE such as Android Studio because the class doesn’t exist yet. -Ignore the error for now; you’ll create the class soon.</p> - -<p>The constructor used here takes two parameters:</p> -<ul> - <li>A {@link -android.content.Context} as its first parameter ({@code this} is used because the {@link -android.app.Activity} class is a subclass of {@link android.content.Context}) - <li>The {@link java.lang.Class} of the app component to which the system should deliver -the {@link android.content.Intent} (in this case, the activity that should be started) -</ul> - -<p>Android Studio indicates that you must import the {@link android.content.Intent} class.</p> - -</li> -<li>At the top of the file, import the {@link android.content.Intent} class: -<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p> -<pre> -import android.content.Intent; -</pre> -<p class="note"><strong>Tip:</strong> In Android Studio, press Alt + Enter (option + return on Mac) - to import missing classes.</p> -</li> - -<!-- I didn't think this was necessary -<div class="sidebox-wrapper"> -<div class="sidebox"> - <h3>Sending an intent to other apps</h3> - <p>The intent created in this lesson is what's considered an <em>explicit intent</em>, because the -{@link android.content.Intent} -specifies the exact app component to which the intent should be given. However, intents -can also be <em>implicit</em>, in which case the {@link android.content.Intent} does not specify -the desired component, but allows any app installed on the device to respond to the intent -as long as it satisfies the meta-data specifications for the action that's specified in various -{@link android.content.Intent} parameters. For more information, see the class about <a -href="{@docRoot}training/basics/intents/index.html">Interacting with Other Apps</a>.</p> -</div> -</div> ---> - -<li>Inside the {@code sendMessage()} method, -use {@link android.app.Activity#findViewById findViewById()} to get the -{@link android.widget.EditText} element. -<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p> -<pre> -public void sendMessage(View view) { - Intent intent = new Intent(this, DisplayMessageActivity.class); - EditText editText = (EditText) findViewById(R.id.edit_message); -} -</pre> -</li> - -<li>At the top of the file, import the {@link android.widget.EditText} class. - <p>In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.</p> -</li> - -<li>Assign the text to a local <code>message</code> variable, and use the -{@link android.content.Intent#putExtra putExtra()} method to add its text value to the intent. -<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p> -<pre> -public void sendMessage(View view) { - Intent intent = new Intent(this, DisplayMessageActivity.class); - EditText editText = (EditText) findViewById(R.id.edit_message); - String message = editText.getText().toString(); - intent.putExtra(EXTRA_MESSAGE, message); -} -</pre> - -<p>An {@link android.content.Intent} can carry data types as key-value -pairs called <em>extras</em>. The {@link android.content.Intent#putExtra putExtra()} method takes the -key name in the first parameter and the value in the second parameter.</p> - -</li> -<li>At the top of the {@code MyActivity} class, add the {@code EXTRA_MESSAGE} definition as -follows: -<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p> -<pre> -public class MyActivity extends AppCompatActivity { - public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE"; - ... -} -</pre> - -<p>For the next activity to query the extra data, you should define the key -for your intent's extra using a public constant. It's generally a good practice to define keys for -intent extras using your app's package name as a prefix. This ensures the keys are unique, in case -your app interacts with other apps.</p> - -</li> - -<!-- <h2 id="StartActivity">Start the Second Activity</h2> --> - -<li>In the {@code sendMessage()} method, to finish the intent, call the -{@link android.app.Activity#startActivity startActivity()} method, passing it the -{@link android.content.Intent} object created in step 1. - -</ol> - -<p>With this new code, the complete {@code sendMessage()} method that's invoked by the Send -button now looks like this:</p> -<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p> -<pre> -/** Called when the user clicks the Send button */ -public void sendMessage(View view) { - Intent intent = new Intent(this, DisplayMessageActivity.class); - EditText editText = (EditText) findViewById(R.id.edit_message); - String message = editText.getText().toString(); - intent.putExtra(EXTRA_MESSAGE, message); - startActivity(intent); -} -</pre> - -<p>The system receives this call and starts an instance of the {@link android.app.Activity} -specified by the {@link android.content.Intent}. Now you need to create the -{@code DisplayMessageActivity} class in order for this to work.</p> - -</li> -</ol> - + <li>In the file <code>res/layout/activity_main.xml</code>, add the + <a href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a> + attribute to the {@link android.widget.Button <Button>} element as + shown below: + <pre><Button + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/button_send" + <b>android:onClick="sendMessage"</b> /> + </pre> + <p>This attribute tells the system to call the <code>sendMessage()</code> + method in your activity whenever a user clicks on the button.</p> + </li> -<h2 id="CreateActivity">Create the Second Activity</h2> + <li>In the file <code>java/com.example.myfirstapp/MainActivity.java</code>, + add the <code>sendMessage()</code> method stub as shown below: -<p>All subclasses of {@link android.app.Activity} must implement the -{@link android.app.Activity#onCreate onCreate()} method. This method is where the activity receives -the intent with the message, then renders the message. Also, the -{@link android.app.Activity#onCreate onCreate()} method must define the activity -layout with the {@link android.app.Activity#setContentView setContentView()} method. This is where -the activity performs the initial setup of the activity components.</p> + <pre>public class MainActivity extends AppCompatActivity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + } -<h3>Create a new activity using Android Studio</h3> + <b>/** Called when the user clicks the Send button */ + public void sendMessage(View view) { + // Do something in response to button + }</b> +}</pre> -<p>Android Studio includes a stub for the -{@link android.app.Activity#onCreate onCreate()} method when you create a new activity. The -<em>New Android Activity</em> window appears.</p> + <p>In order for the system to match this method to the method name given to <a + href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a>, + the signature must be exactly as shown. Specifically, the method must:</p> -<ol> - <li>In Android Studio, in the <code>java</code> directory, select the package, - <strong>com.mycompany.myfirstapp</strong>, right-click, and select - <strong>New > Activity > Blank Activity</strong>.</li> - <li>In the <strong>Choose options</strong> window, fill in the activity details: <ul> - <li><strong>Activity Name</strong>: DisplayMessageActivity</li> - <li><strong>Layout Name</strong>: activity_display_message</li> - <li><strong>Title</strong>: My Message</li> - <li><strong>Hierarchical Parent</strong>: com.mycompany.myfirstapp.MyActivity</li> - <li><strong>Package name</strong>: com.mycompany.myfirstapp</li> + <li>Be public</li> + <li>Have a void return value</li> + <li>Have a {@link android.view.View} as the only parameter (this will be the {@link + android.view.View} that was clicked)</li> </ul> - <p>Click <strong>Finish</strong>.</p> - </li> - -<li>Open the {@code DisplayMessageActivity.java} file. -<p>The class already includes an implementation of the required -{@link android.app.Activity#onCreate onCreate()} method. You update the implementation of this -method later.</p> - -<!-- Android Studio does not create a Fragment placeholder -<p>Also, the file includes a <code>PlaceholderFragment</code> class that extends -{@link android.app.Fragment}. This activity does not implement fragments, but you might use this -later in the training. Fragments decompose application functionality and UI into reusable modules. -For more information on fragments, see the -<a href="{@docRoot}guide/components/fragments.html">Fragments API Guide</a> and follow the training, -<a href="{@docRoot}training/basics/fragments/index.html">Building A Dynamic UI with Fragments</a>. -</p> ---> </li> </ol> -<!-- Not needed for Android Studio -<p class="note"><strong>Note:</strong> Your activity may look different if you did not use -the latest version of the ADT plugin. Make sure you install the latest version of the -<a href="{@docRoot}tools/sdk/eclipse-adt.html">ADT plugin</a> to complete this tutorial.</p> ---> - -<p>If you're developing with Android Studio, you can run the app now, but not much happens. -Clicking the Send button starts the second activity, but it uses -a default "Hello world" layout provided by the template. You'll soon update the -activity to instead display a custom text view.</p> - - -<h3>Create the activity without Android Studio</h3> - -<p>If you're using a different IDE or the command line tools, do the following:</p> +<p>Next, you’ll fill in this method to read the contents of the text field and deliver that text to +another activity.</p> -<ol> -<li>Create a new file named {@code DisplayMessageActivity.java} in the project's <code>src/</code> -directory, next to the original {@code MyActivity.java} file.</li> -<li>Add the following code to the file: +<h2 id="BuildIntent">Build an Intent</h2> +<p>An {@link android.content.Intent} is an object that provides runtime binding + between separate components (such as two activities). The + {@link android.content.Intent} represents an app’s "intent to do something." + You can use intents for a wide variety of tasks, but in this lesson, your intent + starts another activity.</p> -<pre> -public class DisplayMessageActivity extends AppCompatActivity { +<p>In <code>MainActivity.java</code>, add the code shown below to + <code>sendMessage()</code>:</p> +<pre>public class MainActivity extends AppCompatActivity { + <b>public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";</b> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_display_message); - - if (savedInstanceState == null) { - getSupportFragmentManager().beginTransaction() - .add(R.id.container, new PlaceholderFragment()).commit(); - } + setContentView(R.layout.activity_main); } - @Override - public boolean onOptionsItemSelected(MenuItem item) { - // Handle app bar item clicks here. The app bar - // automatically handles clicks on the Home/Up button, so long - // as you specify a parent activity in AndroidManifest.xml. - int id = item.getItemId(); - if (id == R.id.action_settings) { - return true; - } - return super.onOptionsItemSelected(item); + /** Called when the user clicks the Send button */ + public void sendMessage(View view) { + <b>Intent intent = new Intent(this, DisplayMessageActivity.class); + EditText editText = (EditText) findViewById(R.id.edit_message); + String message = editText.getText().toString(); + intent.putExtra(EXTRA_MESSAGE, message); + startActivity(intent);</b> } +}</pre> - /** - * A placeholder fragment containing a simple view. - */ - public static class PlaceholderFragment extends Fragment { - - public PlaceholderFragment() { } +<p class="note"><strong>Note: </strong>Android Studio will display + <code>Cannot resolve symbol</code> errors because the code references classes + like {@link android.content.Intent} and {@link android.widget.EditText} + that have not been imported. To import these classes, you can either 1) + use Android Studio's "import class" functionality by pressing Alt + Enter + (Option + Return on Mac) or 2) manually add import statements at the top of + the file.</p> - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_display_message, - container, false); - return rootView; - } - } -} -</pre> +<p>There’s a lot going on in <code>sendMessage()</code>, so let’s explain + what's going on.</p> -<p class="note"><strong>Note:</strong> If you are using an IDE other than Android Studio, your project -does not contain the {@code activity_display_message} layout that's requested by -{@link android.app.Activity#setContentView setContentView()}. That's OK because -you will update this method later and won't be using that layout.</p> +<p>The {@link android.content.Intent} constructor takes two parameters:</p> +<ul> + <li>A {@link android.content.Context} as its first parameter ({@code this} + is used because the {@link android.app.Activity} class is a subclass of + {@link android.content.Context}) + <li>The {@link java.lang.Class} of the app component to which the system + should deliver the {@link android.content.Intent} (in this case, the + activity that should be started). + <p class="note"><strong>Note:</strong> The reference to + <code>DisplayMessageActivity</code> will raise an error in Android Studio + because the class doesn’t exist yet. Ignore the error for now; you’ll + create the class soon.</p> +</ul> -</li> +<p>The {@link android.content.Intent#putExtra(String, String) putExtra()} + method adds the <code>EditText</code>'s value to the intent. An <code>Intent</code> + can carry data types as key-value pairs called <em>extras</em>. Your key is a + public constant <code>EXTRA_MESSAGE</code> because the next + activity uses the key to retrive the text value. It's a good practice to + define keys for intent extras using your app's package name as a prefix. This + ensures the keys are unique, in case your app interacts with other apps.</p> -<li>To your {@code strings.xml} file, add the new activity's title as follows: -<pre> -<resources> - ... - <string name="title_activity_display_message">My Message</string> -</resources> -</pre> -</li> +<p>The {@link android.app.Activity#startActivity(Intent) startActivity()} + method starts an instance of the <code>DisplayMessageActivity</code> specified + by the {@link android.content.Intent}. Now you need to create the class.</p> -<li>In your manifest file, <code>AndroidManifest.xml</code>, within the <code>Application</code> -element, add the -<a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element -for your {@code DisplayMessageActivity} class, as follows: - -<pre> -<application ... > - ... - <activity - android:name="com.mycompany.myfirstapp.DisplayMessageActivity" - android:label="@string/title_activity_display_message" - android:parentActivityName="com.mycompany.myfirstapp.MyActivity" > - <meta-data - android:name="android.support.PARENT_ACTIVITY" - android:value="com.mycompany.myfirstapp.MyActivity" /> - </activity> -</application> -</pre> +<h2 id="CreateActivity">Create the Second Activity</h2> -</li> +<ol> + <li>In the <b>Project</b> window, right-click the <b>app</b> folder and select + <strong>New > Activity > Empty Activity</strong>.</li> + <li>In the <strong>Configure Activity</strong> window, enter + "DisplayMessageActivity" for <strong>Activity Name</strong> and click + <strong>Finish</strong> + </li> </ol> -<p>The <a href="{@docRoot}guide/topics/manifest/activity-element.html#parent">{@code -android:parentActivityName}</a> attribute declares the name of this activity's parent activity -within the app's logical hierarchy. The system uses this value -to implement default navigation behaviors, such as <a -href="{@docRoot}design/patterns/navigation.html">Up navigation</a> on -Android 4.1 (API level 16) and higher. You can provide the same navigation behaviors for -older versions of Android by using the -<a href="{@docRoot}tools/support-library/index.html">Support Library</a> and adding -the <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code -<meta-data>}</a> element as shown here.</p> - -<p class="note"><strong>Note:</strong> Your Android SDK should already include -the latest Android Support Library, which you installed during the -<a href="{@docRoot}studio/intro/update.html">Adding SDK Packages</a> step. -When using the templates in Android Studio, the Support Library is automatically added to your app project -(you can see the library's JAR file listed under <em>Android Dependencies</em>). If you're not using -Android Studio, you need to manually add the library to your project—follow the guide for <a -href="{@docRoot}tools/support-library/setup.html">setting up the Support Library</a> -then return here.</p> - -<p>If you're using a different IDE than Android Studio, don't worry that the app won't yet compile. -You'll soon update the activity to display a custom text view.</p> - - -<h2 id="ReceiveIntent">Receive the Intent</h2> - -<p>Every {@link android.app.Activity} is invoked by an {@link android.content.Intent}, regardless of -how the user navigated there. You can get the {@link android.content.Intent} that started your -activity by calling {@link android.app.Activity#getIntent()} and retrieve the data contained -within the intent.</p> +<p>Android Studio automatically does three things:</p> +<ul> + <li>Creates the class <code>DisplayMessageActivity.java</code> with an + implementation of the required {@link android.app.Activity#onCreate(Bundle) onCreate()} + method.</li> + <li>Creates the corresponding layout file <code>activity_display_message.xml</code> + </li> + <li>Adds the required + <a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a> + element in <code>AndroidManifest.xml</code>. +</ul> -<ol> -<li>In the <code>java/com.mycompany.myfirstapp</code> directory, edit the - {@code DisplayMessageActivity.java} file.</li> -<li>Get the intent and assign it to a local variable. -<pre> -Intent intent = getIntent(); -</pre> -</li> -<li>At the top of the file, import the {@link android.content.Intent} class. - <p>In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.</p> -</li> -<li>Extract the message delivered by {@code MyActivity} with the -{@link android.content.Intent#getStringExtra getStringExtra()} method. -<pre> -String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE); -</pre> -</li> -</ol> +<p>If you run the app and click the Send button on the first activity, the + second activity starts but is empty. This is because the second activity uses + the default empty layout provided by the template.</p> <h2 id="DisplayMessage">Display the Message</h2> +<p>Now you will modify the second activity to display the message that was passed +by the first activity.</p> <ol> -<li>In the res/layout directory, edit the {@code content_display_message.xml} file.</li> -<li>Add an {@code android:id} attribute to the {@code RelativeLayout}. -You need this attribute to reference the object from your app code.</li> - -<pre> -< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" -... -android:id="@+id/content"> -</RelativeLayout> -</pre> -<li>Switch back to editing {@code DisplayMessageActivity.java}.</li> - - -<li>In the {@link android.app.Activity#onCreate onCreate()} method, create a {@link android.widget.TextView} object. -<pre> -TextView textView = new TextView(this); -</pre> -</li> -<li>Set the text size and message with {@link android.widget.TextView#setText setText()}. -<pre> -textView.setTextSize(40); -textView.setText(message); -</pre> -</li> -<li>Add the {@link android.widget.TextView} to the {@link android.widget.RelativeLayout} -identified by {@code R.id.content}. -<pre> -RelativeLayout layout = (RelativeLayout) findViewById(R.id.content); -layout.addView(textView); -</pre> -</li> -<li>At the top of the file, import the {@link android.widget.TextView} class. - <p>In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.</p> -</li> -</ol> - -<p>The complete {@link android.app.Activity#onCreate onCreate()} method for {@code -DisplayMessageActivity} now looks like this:</p> - -<pre> -@Override + <li>In {@code DisplayMessageActivity.java}, add the following code to the + <code>onCreate()</code> method: + <pre>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_message); - Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - - FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); - fab.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) - .setAction("Action", null) - .show(); - } - }); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); Intent intent = getIntent(); - String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE); + String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); TextView textView = new TextView(this); textView.setTextSize(40); textView.setText(message); - RelativeLayout layout = (RelativeLayout) findViewById(R.id.content); + ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message); layout.addView(textView); -</pre> +}</pre> + </li> + <li>Press Alt + Enter (option + return on Mac) to import missing classes.</li> +</ol> + +<p>There’s a lot going on here, so let’s explain:</p> + +<ol> + <li>The call {@link android.app.Activity#getIntent()} grabs the intent + that started the activity. Every {@link android.app.Activity} is invoked by an + {@link android.content.Intent}, regardless of how the user navigated there. + The call {@link android.content.Intent#getStringExtra(String) getStringExtra()} + retrieves the data from the first activity.</li> + <li>You programmatically create a {@link android.widget.TextView} and set + its size and message. + </li> + <li>You add the <code>TextView</code> to the layout identified by + {@code R.id.activity_display_message}. You cast the layout to + {@link android.view.ViewGroup} because it is the superclass of all layouts and + contains the {@link android.view.ViewGroup#addView(View) addView()} + method.</li> +</ol> + +<p class="note"><strong>Note: </strong>The XML layout generated by previous + versions of Android Studio might not include the <code>android:id</code> + attribute. The call <code>findViewById()</code> will fail if the layout + does not have the <code>android:id</code> attribute. If this is the case, + open <code>activity_display_message.xml</code> and add the attribute + <code>android:id="@+id/activity_display_message"</code> to the layout element. +</p> <p>You can now run the app. When it opens, type a message in the text field, and click <strong>Send</strong>. The second activity replaces the first one on the screen, showing @@ -513,8 +234,4 @@ the message you entered in the first activity.</p> <p>That's it, you've built your first Android app!</p> -<p>To learn more, follow the link below to the next class.</p> - - - - +<p>To learn more, follow the link below to the next class.</p>
\ No newline at end of file diff --git a/docs/html/training/gestures/index.jd b/docs/html/training/gestures/index.jd index fad1afafbbe9..1b8f4c120a20 100644 --- a/docs/html/training/gestures/index.jd +++ b/docs/html/training/gestures/index.jd @@ -48,7 +48,7 @@ interaction to your app can greatly increase its usefulness and appeal.</p> provide users with a consistent, intuitive experience, your app should follow the accepted Android conventions for touch gestures. The <a href="http://developer.android.com/design/patterns/gestures.html">Gestures -design guide</a><a href="{@docRoot}design/patterns/notifications.html"></a> +design guide</a><a href="https://material.google.com/patterns/notifications.html"></a> shows you how to use common gestures in Android apps. Also see the Design Guide for <a href="{@docRoot}design/style/touch-feedback.html">Touch Feedback</a>. </p> diff --git a/docs/html/training/in-app-billing/preparing-iab-app.jd b/docs/html/training/in-app-billing/preparing-iab-app.jd index 2c6e9a074d31..780f2f800a7c 100755..100644 --- a/docs/html/training/in-app-billing/preparing-iab-app.jd +++ b/docs/html/training/in-app-billing/preparing-iab-app.jd @@ -31,23 +31,32 @@ next.link=list-iab-products.html </div> <a class="notice-developers-video wide" -href="https://www.youtube.com/watch?v=UvCl5Xx7Z5o"> +href="https://www.youtube.com/watch?v=UvCl5Xx7Z5o" class="external-link"> <div> <h3>Video</h3> <p>Implementing Freemium</p> </div> </a> -<p>Before you can start using the In-app Billing service, you'll need to add the library that contains the In-app Billing Version 3 API to your Android project. You also need to set the permissions for your application to communicate with Google Play. In addition, you'll need to establish a connection between your application and Google Play. You should also verify that the In-app Billing API version that you are using in your application is supported by Google Play.</p> +<p>Before you can start using the In-app Billing service, you need to add the library that + contains the In-app Billing Version 3 API to your Android project. You also need to set the + permissions for your application to communicate with Google Play. In addition, you need to + establish a connection between your application and Google Play. You must also verify that + the In-app Billing API version that you are using in your application is supported + by Google Play.</p> <h2 id="GetSample">Download the Sample Application</h2> -<p>In this training class, you will use a reference implementation for the In-app Billing Version 3 API called the {@code TrivialDrive} sample application. The sample includes convenience classes to quickly set up the In-app Billing service, marshal and unmarshal data types, and handle In-app Billing requests from the main thread of your application.</p> -<p>To download the sample application:</p> +<p>In this training class, you use a reference implementation for the In-app Billing + Version 3 API + called the {@code TrivialDrive} sample application. The sample includes convenience classes to + quickly set up the In-app Billing service, marshal and unmarshal data types, and handle In-app + Billing requests from the main thread of your application.</p> +<p>To download the sample application, follow these steps:</p> <ol> <li>Open Android Studio and then close any open projects until you are presented with the welcome screen.</li> -<li>Choose <strong>Import an Android code sample</strong> from the - <strong>Quick Start</strong> list on the right side the window.</li> +<li>From the <strong>Quick Start</strong> list on the right side of the window, choose + <strong>Import an Android code sample</strong>.</li> <li>Type {@code Trivial Drive} into the search bar and select the <strong>Trivial Drive</strong> sample.</li> <li>Follow the rest of the instructions in the <strong>Import Sample</strong> @@ -56,66 +65,121 @@ presented with the welcome screen.</li> </ol> <p>Alternatively, you can use {@code git} to manually clone - the repository from <a + the repository from the <a href="https://github.com/googlesamples/android-play-billing" - class="external-link">https://github.com/googlesamples/android-play-billing</a></p> + class="external-link">Google Samples</a> GitHub site.</p> <h2 id="AddToDevConsole">Add Your Application to the Developer Console</h2> -<p>The Google Play Developer Console is where you publish your In-app Billing application and manage the various digital goods that are available for purchase from your application. When you create a new application entry in the Developer Console, it automatically generates a public license key for your application. You will need this key to establish a trusted connection from your application to the Google Play servers. You only need to generate this key once per application, and don’t need to repeat these steps when you update the APK file for your application.</p> -<p>To add your application to the Developer Console:</p> +<p>The Google Play Developer Console is where you publish your In-app Billing application + and manage the various digital products that are available for purchase from your + application. + When you create a new application entry in the Developer Console, it automatically generates + a public license key for your application. You need this key to establish a trusted connection + from your application to the Google Play servers. You need to generate this key only once + per application, and you don’t need to repeat these steps when you update the APK file for + your application.</p> +<p>To add your application to the Developer Console, follow these steps:</p> <ol> -<li>Go to the <a href="http://play.google.com/apps/publish">Google Play Developer Console</a> site and log in. You will need to register for a new developer account, if you have not registered previously. To sell in-app items, you also need to have a <a href="http://www.google.com/wallet/merchants.html">Google payments</a> merchant account.</li> -<li>Click on <strong>Try the new design</strong> to access the preview version of the Developer Console, if you are not already logged on to that version. </li> -<li>In the <strong>All Applications</strong> tab, add a new application entry. +<li>Go to the <a href="http://play.google.com/apps/publish" class="external-link"> +Google Play Developer Console</a> + site and log in. If you have not registered previously, you need to register for a new + developer account. To sell in-app products, you also need a + <a href="http://www.google.com/wallet/merchants.html" class="external-link"> + Google payments</a> merchant account.</li> + +<li>In the <strong>All Applications</strong> tab, complete these steps to add a new + application entry: <ol type="a"> <li>Click <strong>Add new application</strong>.</li> <li>Enter a name for your new In-app Billing application.</li> <li>Click <strong>Prepare Store Listing</strong>.</li> </ol> </li> -<li>In the <strong>Services & APIs</strong> tab, find and make a note of the public license key that Google Play generated for your application. This is a Base64 string that you will need to include in your application code later.</li> +<li>In the <strong>Services & APIs</strong> tab, find and make a note of the public license key + that Google Play generated for your application. This is a Base64 string that you need to + include in your application code later.</li> </ol> <p>Your application should now appear in the list of applications in Developer Console.</p> <h2 id="AddLibrary">Add the In-app Billing Library</h2> -<p>To use the In-app Billing Version 3 features, you must add the {@code IInAppBillingService.aidl} file to your Android project. This Android Interface Definition Language (AIDL) file defines the interface to the Google Play service.</p> -<p>You can find the {@code IInAppBillingService.aidl} file in the provided sample app. Depending on whether you are creating a new application or modifying an existing application, follow the instructions below to add the In-app Billing Library to your project.</p> -<h3>New Project</h3> -<p>To add the In-app Billing Version 3 library to your new In-app Billing project:</p> +<p>To use the In-app Billing Version 3 features, you must add the + {@code IInAppBillingService.aidl} + file to your Android project. This Android Interface Definition Language + (AIDL) file defines the + interface to the Google Play service.</p> +<p>You can find the {@code IInAppBillingService.aidl} file in the provided sample app. + To add the + In-app Billing library to your project, follow the instructions below for a new or + existing project.</p> +<h3>Adding in-app billing to a new project</h3> +<p>To add the In-app Billing Version 3 library to a new project, follow these steps:</p> <ol> <li>Copy the {@code TrivialDrive} sample files into your Android project.</li> -<li>Modify the package name in the files you copied to use the package name for your project. In Android Studio, you can use this shortcut: right-click the package name, then select <strong>Refactor</strong> > <strong>Rename</strong>.</li> -<li>Open the {@code AndroidManifest.xml} file and update the package attribute value to use the package name for your project.</li> -<li>Fix import statements as needed so that your project compiles correctly. In Android Studio, you can use this shortcut: press <strong>Ctrl+Shift+O</strong> in each file showing errors.</li> -<li>Modify the sample to create your own application. Remember to copy the Base64 public license key for your application from the Developer Console over to your {@code MainActivity.java}.</li> +<li>Modify the package name in the files that you copied to use the package name + for your project. + In Android Studio, you can right-click the package name and then + select <strong>Refactor</strong> > <strong>Rename</strong>.</li> +<li>Open the {@code AndroidManifest.xml} file and update the package attribute value to + use the package name for your project.</li> +<li>Fix import statements as needed so that your project compiles correctly. + In Android Studio, you can press <strong>Ctrl+Shift+O</strong> + in each file showing errors.</li> +<li>Modify the sample to create your own application. Remember to copy the Base64 + public license key for your application from the Developer Console to + your {@code MainActivity.java}.</li> </ol> -<h3>Existing Project</h3> -<p>To add the In-app Billing Version 3 library to your existing In-app Billing project:</p> +<h3>Adding in-app billing to an existing project</h3> +<p>To add the In-app Billing Version 3 library to an existing project, follow these steps:</p> <ol> <li>Copy the {@code IInAppBillingService.aidl} file to your Android project. <ul> - <li>In Android Studio: Create a directory named {@code aidl} under {@code src/main}, add a new - package {@code com.android.vending.billing} in this directory, and import the + <li>In Android Studio: Create a directory named {@code aidl} under {@code src/main}, + add a new + package {@code com.android.vending.billing} in this directory, and then import the {@code IInAppBillingService.aidl} file into this package.</li> - <li>In other dev environments: Create the following directory {@code /src/com/android/vending/billing} and copy the {@code IInAppBillingService.aidl} file into this directory.</li> + <li>In other dev environments: Create the following directory + {@code /src/com/android/vending/billing} and copy the {@code IInAppBillingService.aidl} + file into this directory.</li> </ul> </li> -<li>Build your application. You should see a generated file named {@code IInAppBillingService.java} in the {@code /gen} directory of your project.</li> -<li>Add the helper classes from the {@code /util} directory of the {@code TrivialDrive} sample to your project. Remember to change the package name declarations in those files accordingly so that your project compiles correctly.</li> +<li>Build your application. You should see a generated file named + {@code IInAppBillingService.java} + in the {@code /gen} directory of your project.</li> +<li>Add the helper classes from the {@code /util} directory of the {@code TrivialDrive} + sample to + your project. Remember to change the package name declarations in those files + accordingly so + that your project compiles correctly.</li> </ol> <p>Your project should now contain the In-app Billing Version 3 library.</p> <h2 id="SetPermission">Set the Billing Permission</h2> -<p>Your app needs to have permission to communicate request and response messages to the Google Play’s billing service. To give your app the necessary permission, add this line in your {@code AndroidManifest.xml} manifest file:</p> +<p>Your app needs to have permission to communicate request and response messages to + the Google Play billing service. To give your app the necessary permission, add the following + line in your {@code AndroidManifest.xml} manifest file:</p> <pre> <uses-permission android:name="com.android.vending.BILLING" /> </pre> <h2 id="Connect">Initiate a Connection with Google Play</h2> -<p>You must bind your Activity to Google Play’s In-app Billing service to send In-app Billing requests to Google Play from your application. The convenience classes provided in the sample handles the binding to the In-app Billing service, so you don’t have to manage the network connection directly.</p> -<p>To set up synchronous communication with Google Play, create an {@code IabHelper} instance in your activity's {@code onCreate} method. In the constructor, pass in the {@code Context} for the activity, along with a string containing the public license key that was generated earlier by the Google Play Developer Console. </p> -<p class="note"><strong>Security Recommendation:</strong> It is highly recommended that you do not hard-code the exact public license key string value as provided by Google Play. Instead, you can construct the whole public license key string at runtime from substrings, or retrieve it from an encrypted store, before passing it to the constructor. This approach makes it more difficult for malicious third-parties to modify the public license key string in your APK file.</p> +<p>To send In-app + Billing requests to Google Play from your application, you must bind your Activity + to the Google Play In-app Billing service. The sample includes convenience classes + that handle the binding to the In-app Billing service, so you don’t have to + manage the network connection directly.</p> +<p>To set up synchronous communication with Google Play, create an {@code IabHelper} + instance in your activity's {@code onCreate} method, as shown in the following example. + In the constructor, pass in the {@code Context} for the activity along with a string + containing the public license key that was generated earlier by the Google Play + Developer Console. +</p> +<p class="caution"><strong>Security Recommendation:</strong> Google highly recommends that + you do not hard-code the exact public license key string value as provided by Google Play. + Instead, construct the whole public license key string at runtime from substrings + or retrieve it from an encrypted store before passing it to the constructor. + This approach makes it more difficult for malicious third parties to modify the public + license key string in your APK file.</p> <pre> IabHelper mHelper; @@ -130,13 +194,20 @@ public void onCreate(Bundle savedInstanceState) { } </pre> -<p>Next, perform the service binding by calling the {@code startSetup} method on the {@code IabHelper} instance that you created. Pass the method an {@code OnIabSetupFinishedListener} instance, which is called once the {@code IabHelper} completes the asynchronous setup operation. As part of the setup process, the {@code IabHelper} also checks if the In-app Billing Version 3 API is supported by Google Play. If the API version is not supported, or if an error occured while establishing the service binding, the listener is notified and passed an {@code IabResult} object with the error message.</p> +<p>Next, perform the service binding by calling the {@code startSetup} method on the + {@code IabHelper} instance that you created, as shown in the following example. + Pass the method an {@code OnIabSetupFinishedListener} instance, which is called once + the {@code IabHelper} completes the asynchronous setup operation. As part of the + setup process, the {@code IabHelper} also checks if the In-app Billing Version 3 API + is supported by Google Play. If the API version is not supported, or if an error occurs + while establishing the service binding, the listener is notified and passed an + {@code IabResult} object with the error message.</p> <pre> mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { if (!result.isSuccess()) { - // Oh noes, there was a problem. + // Oh no, there was a problem. Log.d(TAG, "Problem setting up In-app Billing: " + result); } // Hooray, IAB is fully set up! @@ -144,9 +215,18 @@ mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { }); </pre> -<p>If the setup completed successfully, you can now use the {@code mHelper} reference to communicate with the Google Play service. When your application is launched, it is a good practice to query Google Play to find out what in-app items are owned by a user. This is covered further in the <a href="{@docRoot}training/in-app-billing/purchase-iab-products.html#QueryPurchases">Query Purchased Items</a> section.</p> +<p>If the setup completed successfully, you can now use the {@code mHelper} reference + to communicate with the Google Play service. When your application is launched, it is + a good practice to query Google Play to find out what in-app items are owned by a user. + This is covered further in the + <a href="{@docRoot}training/in-app-billing/purchase-iab-products.html#QueryPurchases"> + Query Purchased Items</a> section.</p> -<p class="note"><strong>Important:</strong> Remember to unbind from the In-app Billing service when you are done with your activity. If you don’t unbind, the open service connection could cause your device’s performance to degrade. To unbind and free your system resources, call the {@code IabHelper}'s {@code dispose} method when your {@code Activity} is destroyed.</p> +<p class="caution"><strong>Important:</strong> Remember to unbind from the In-app Billing service + when you are done with your activity. If you don’t unbind, the open service connection could + degrade device performance. To unbind and free your system resources, call the + {@code IabHelper}'s {@code dispose} method when your {@code Activity} is destroyed, + as shown in the following example.</p> <pre> @Override @@ -156,8 +236,3 @@ public void onDestroy() { mHelper = null; } </pre> - - - - - diff --git a/docs/html/training/notify-user/build-notification.jd b/docs/html/training/notify-user/build-notification.jd index 2f96a20985ed..baa10748c4ec 100644 --- a/docs/html/training/notify-user/build-notification.jd +++ b/docs/html/training/notify-user/build-notification.jd @@ -31,7 +31,7 @@ trainingnavtop=true </a> </li> <li> - <a href="{@docRoot}design/patterns/notifications.html">Notifications</a> Design Guide + <a href="https://material.google.com/patterns/notifications.html">Notifications</a> Design Guide </li> </ul> diff --git a/docs/html/training/notify-user/display-progress.jd b/docs/html/training/notify-user/display-progress.jd index e2cf033d7b6c..9018eb1950c0 100644 --- a/docs/html/training/notify-user/display-progress.jd +++ b/docs/html/training/notify-user/display-progress.jd @@ -29,7 +29,7 @@ trainingnavtop=true </a> </li> <li> - <a href="{@docRoot}design/patterns/notifications.html">Notifications</a> Design Guide + <a href="https://material.google.com/patterns/notifications.html">Notifications</a> Design Guide </li> </ul> diff --git a/docs/html/training/notify-user/expanded.jd b/docs/html/training/notify-user/expanded.jd index 23d85d438092..60853caf047b 100644 --- a/docs/html/training/notify-user/expanded.jd +++ b/docs/html/training/notify-user/expanded.jd @@ -29,7 +29,7 @@ trainingnavtop=true </a> </li> <li> - <a href="{@docRoot}design/patterns/notifications.html">Notifications</a> Design Guide + <a href="https://material.google.com/patterns/notifications.html">Notifications</a> Design Guide </li> </ul> diff --git a/docs/html/training/notify-user/index.jd b/docs/html/training/notify-user/index.jd index 57efd6512849..4d930e0b2b94 100644 --- a/docs/html/training/notify-user/index.jd +++ b/docs/html/training/notify-user/index.jd @@ -27,7 +27,7 @@ startpage=true </a> </li> <li> - <a href="{@docRoot}design/patterns/notifications.html">Notifications</a> Design Guide + <a href="https://material.google.com/patterns/notifications.html">Notifications</a> Design Guide </li> </ul> @@ -50,7 +50,7 @@ class="button">Download the sample</a> </p> <p> - The <a href="{@docRoot}design/patterns/notifications.html">Notifications design guide</a> shows + The <a href="https://material.google.com/patterns/notifications.html">Notifications design guide</a> shows you how to design effective notifications and when to use them. This class shows you how to implement the most common notification designs. </p> diff --git a/docs/html/training/notify-user/managing.jd b/docs/html/training/notify-user/managing.jd index fc12cfb9f32a..c68d6f9ab04c 100644 --- a/docs/html/training/notify-user/managing.jd +++ b/docs/html/training/notify-user/managing.jd @@ -29,7 +29,7 @@ trainingnavtop=true </a> </li> <li> - <a href="{@docRoot}design/patterns/notifications.html">Notifications</a> Design Guide + <a href="https://material.google.com/patterns/notifications.html">Notifications</a> Design Guide </li> </ul> diff --git a/docs/html/training/notify-user/navigation.jd b/docs/html/training/notify-user/navigation.jd index cdb7f3d6e0c4..65f8d48ba375 100644 --- a/docs/html/training/notify-user/navigation.jd +++ b/docs/html/training/notify-user/navigation.jd @@ -29,7 +29,7 @@ trainingnavtop=true </a> </li> <li> - <a href="{@docRoot}design/patterns/notifications.html">Notifications</a> Design Guide + <a href="https://material.google.com/patterns/notifications.html">Notifications</a> Design Guide </li> </ul> diff --git a/docs/html/training/safebrowsing/index.jd b/docs/html/training/safebrowsing/index.jd new file mode 100644 index 000000000000..c6c72bfd1460 --- /dev/null +++ b/docs/html/training/safebrowsing/index.jd @@ -0,0 +1,315 @@ +page.title=Checking URLs with the Safe Browsing API + +@jd:body + + +<div id="tb-wrapper"> + <div id="tb"> + <h2> + In this document + </h2> + + <ol> + <li> + <a href="#tos">Terms of Service</a> + </li> + + <li> + <a href="#api-key">Requesting and Registering an Android API Key</a> + <ol> + <li> + <a href="#manifest">Adding the Android API to your + AndroidManifest.xml</a> + </li> + </ol> + </li> + + <li> + <a href="#connect-google-play">Connect to Google Play Services</a> + </li> + + <li> + <a href="#url-check">Requesting a URL Check</a> + <ol> + <li> + <a href="#threat-types">Specifying threat types of interest</a> + </li> + + <li> + <a href="#url-check-request">Send the URL check request</a> + </li> + + <li> + <a href="#url-check-response">Read the URL check response</a> + </li> + </ol> + </li> + + <li> + <a href="#warning-lang">Suggested Warning Language</a> + </li> + </ol> + </div> +</div> + +<p> + SafetyNet provides services for determining whether a URL has been marked as + a known threat by Google. +</p> + +<p> + The service provides an API your app can use to determine whether a + particular URL has been classified by Google as a known threat. Internally, + SafetyNet implements a client for the Safe Browsing Network Protocol v4 + developed by Google. Both the client code and the v4 network protocol were + designed to preserve users' privacy, as well as keep battery and bandwidth + consumption to a minimum. This API allows you to take full advantage of + Google's Safe Browsing service on Android in the most resource-optimized way, + and without having to implement its network protocol. +</p> + +<p> + This document shows you how to use SafetyNet for checking a URL for threat + types of interest. +</p> + +<h2 id="tos"> + Terms of Service +</h2> + +<p> + By using the Safe Browsing API, you consent to be bound by the <a href= + "https://developers.google.com/safe-browsing/terms">Terms of Service</a>. + Please read and understand all applicable terms and policies before accessing + the Safe Browsing API. +</p> + +<h2 id="api-key"> + Requesting and Registering an Android API Key +</h2> + +<p> + To create an API key, complete the following steps: +</p> + +<ol> + <li>Go to the <a href="https://console.developers.google.com/project" + class="external-link">Google Developers Console</a>. + </li> + + <li>On the upper toolbar, choose <strong>Select a project > + <em>your-project-name</em></strong>. + </li> + + <li>In the search box, enter <em>Safe Browsing APIs</em>; when the Safe + Browsing API name appears in the table, select it. + </li> + + <li>After the page redisplays, select <strong>Enable</strong> then select + <strong>Go to Credentials</strong>. + </li> + + <li>When the <em>Add credentials to your project</em> window appears, choose + your parameters then select <strong>What credentials do I need?</strong>. + </li> + + <li>Enter a name for your API key then select <strong>Create API + key</strong>. + </li> + + <li> + <p> + Your new API key appears; copy and paste this key for future use. + </p> + + <p class="note"> + <strong>Note:</strong> Your API key allows you to perform a URL check + 10,000 times each day. The key, in this instance, should just be a + hexadecimal string, not part of a URL. + </p> + </li> + + <li>Select <strong>Done</strong> to complete the process. + </li> +</ol> + +<p> + If you need more help, check out the <a href= + "https://developers.google.com/console/help/new/">Google Developers Console + Help Center</a>. +</p> + +<h3 id="manifest"> + Adding the Android API key to your AndroidManifest.xml +</h3> + +<p> + Once your key has been whitelisted, you need to add the key to the + <code>AndroidManifest.xml</code> file for your app: +</p> + +<pre> +<application> + + ... + + <!-- SafetyNet API metadata --> + <meta-data android:name="com.google.android.safetynet.API_KEY" + android:value="<var>your-API-key</var>" /> + + ... + +</application> +</pre> +<h2 id="connect-google-play"> + Connect to Google Play Services +</h2> + +<p> + The SafetyNet API is part of Google Play services. To connect to the API, you + need to create an instance of the Google Play services API client. For + details about using the client in your app, see <a href= + "https://developers.google.com/android/guides/api-client#Starting">Accessing + Google APIs</a>. Once you have established a connection to Google Play + services, you can use the Google API client classes to connect to the + SafetyNet API. +</p> + +<p> + To connect to the API, in your activity's <code><a href= + "{@docRoot}reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code> + method, create an instance of Google API Client using <code><a href= + "https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.Builder"> + GoogleApiClient.Builder</a></code>. Use the builder to add the SafetyNet API, + as shown in the following code example: +</p> + +<pre> +protected synchronized void buildGoogleApiClient() { + mGoogleApiClient = new GoogleApiClient.Builder(this) + .addApi(SafetyNet.API) + .addConnectionCallbacks(myMainActivity.this) + .build(); +} +</pre> +<p class="note"> + <strong>Note:</strong> You can only call these methods after your app has + established a connection to Google Play services by receiving the <code> + <a href="https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.ConnectionCallbacks#public-methods"> + onConnected()</a></code> callback. For details about listening for a completed + client connection, see <a href= + "https://developers.google.com/android/guides/api-client#Starting">Accessing + Google APIs</a>. +</p> + +<h2 id="url-check"> + Requesting a URL Check +</h2> + +<p> + A URL check allows your app to determine if a URL has been marked as a threat + of interest. Some threat types may not be of interest to your particular + app, and the API allows you to choose which threat types are important for + your needs. You can specify multiple threat types of interest. +</p> + +<h3 id="threat-types"> + Specifying threat types of interest +</h3> + +<p> + The constants in the {@code SafeBrowsingThreat} class contain the + currently-supported threat types: +</p> + +<pre> +package com.google.android.gms.safetynet; + +public class SafeBrowsingThreat { + + /** + * This threat type identifies URLs of pages that are flagged as containing potentially + * harmful applications. + */ + public static final int TYPE_POTENTIALLY_HARMFUL_APPLICATION = 4; + + /** + * This threat type identifies URLs of pages that are flagged as containing social + * engineering threats. + */ + public static final int TYPE_SOCIAL_ENGINEERING = 5; +} +</pre> +<p> + When using the API, you must use constants that are not marked as deprecated. + You add threat type constants as arguments to the API. You may add as many + threat type constants as is required for your app. +</p> + +<h3 id="url-check-request"> + Send the URL check request +</h3> + +<p> + The API is agnostic to the scheme used, so you can pass the URL with or + without a scheme. For example, either +</p> + +<pre> +String url = "https://www.google.com"; +</pre> +<p> + or +</p> + +<pre> +String url = "www.google.com"; +</pre> +<p> + is valid. +</p> + +<pre> +SafetyNet.SafetyNetApi.lookupUri(mGoogleApiClient, url, + SafeBrowsingThreat.TYPE_POTENTIALLY_HARMFUL_APPLICATION, + SafeBrowsingThreat.TYPE_SOCIAL_ENGINEERING) + .setResultCallback( + new ResultCallback<SafetyNetApi.SafeBrowsingResult>() { + + @Override + public void onResult(SafetyNetApi.SafeBrowsingResult result) { + Status status = result.getStatus(); + if ((status != null) && status.isSuccess()) { + // Indicates communication with the service was successful. + // Identify any detected threats. + if (result.getDetectedThreats().isEmpty()) { + + } + } else { + // An error occurred. Let the user proceed without warning. + } + } +}); +</pre> +<h3 id="url-check-response"> + Read the URL check response +</h3> + +<p> + The result is provided as a list of {@code SafeBrowsingThreat} objects by + calling the {@code SafetyNetApi.SafeBrowsingResult.getDetectedThreats()} + method of the returned {@code SafetyNetApi.SafeBrowsingResult} object. If the + list is empty, no threats were detected; otherwise, calling {@code + SafeBrowsingThreat.getThreatType()} on each element in the list enumerates + the threats that were detected. +</p> + +<h2 id="warning-lang"> + Suggested Warning Language +</h2> + +<p> + Please see the Safe Browsing API Developer's Guide for <a href= + "https://developers.google.com/safe-browsing/v4/usage-limits#suggested--warning-language"> + suggested warning language</a>. +</p>
\ No newline at end of file diff --git a/docs/html/training/training_toc.cs b/docs/html/training/training_toc.cs index e2aa5f4dabe7..d0dccba64d35 100644 --- a/docs/html/training/training_toc.cs +++ b/docs/html/training/training_toc.cs @@ -656,7 +656,7 @@ description= "How to sync and back up app and user data to remote web services in the cloud and how to restore the data back to multiple devices." - >Syncing to the Cloud</a> + >Backing up App Data to the Cloud</a> </div> <ul> <li><a href="<?cs var:toroot ?>training/backup/autosyncapi.html"> diff --git a/docs/html/training/wearables/notifications/creating.jd b/docs/html/training/wearables/notifications/creating.jd index 6f8497a21ec4..5663b585b94e 100644 --- a/docs/html/training/wearables/notifications/creating.jd +++ b/docs/html/training/wearables/notifications/creating.jd @@ -28,7 +28,7 @@ notifications properly, whether they appear on a handheld or wearable. <p class="note"><strong>Note:</strong> Notifications using {@link android.widget.RemoteViews} are stripped of custom -layouts and the wearable only displays the text and icons. However, you can create +layouts and the wearable only displays the text and icons. However, you can <a href="{@docRoot}training/wearables/apps/layouts.html#CustomNotifications">create custom notifications</a> that use custom card layouts by creating a wearable app that runs on the wearable device.</p> diff --git a/docs/html/wear/preview/api-overview.jd b/docs/html/wear/preview/api-overview.jd index 42336244e4e6..0b3ac6bf4b2d 100644 --- a/docs/html/wear/preview/api-overview.jd +++ b/docs/html/wear/preview/api-overview.jd @@ -45,19 +45,19 @@ page.image=images/cards/card-n-apis_2x.png <p> The Android Wear Preview API is still in active development, but you can try it now as part of the Wear 2.0 Developer Preview. The sections below - highlight some of the new features for Wear developers. + highlight some of the new features for Android Wear developers. </p> <h2 id="ui">User Interface Improvements</h2> -<p>The preview introduces powerful additions to the user interface, opening up -exciting possibilities to developers. -A complication is any feature in a watch face that displays more than hours and -minutes. With the Complications API, - watch faces can display extra information and separate apps can expose complication - data. -The navigation and action drawers provide users with new ways to interact with apps. +<p> + The preview introduces powerful additions to the user interface, opening up + exciting possibilities to developers. A complication + is any feature in a watch face that displays more than hours and + minutes. With the Complications API, watch faces can display extra information + and separate apps can expose complication data. The navigation and action + drawers provide users with new ways to interact with apps. </p> @@ -69,8 +69,8 @@ The navigation and action drawers provide users with new ways to interact with a A <a href= "https://en.wikipedia.org/wiki/Complication_(horology)">complication</a> is a feature of a watch face that displays more than hours and minutes, such as a - battery indicator or a step counter. The Complications API helps watch face - developers create these features visual features and data connections they + battery indicator or a step counter. The Complications API thus helps watch face + developers create visual features and the data connections they require. </p> |