diff --git a/docs/html-intl/intl/es/about/versions/android-5.0.jd b/docs/html-intl/intl/es/about/versions/android-5.0.jd index c94a140c22d4c..4d50584ac24d3 100644 --- a/docs/html-intl/intl/es/about/versions/android-5.0.jd +++ b/docs/html-intl/intl/es/about/versions/android-5.0.jd @@ -428,7 +428,7 @@ sdk.platform.apiLevel=21

Cuando el sistema detecta una red adecuada, se conecta a la red e invoca la devolución de llamada {@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()}. Puedes usar el objeto {@link android.net.Network} de la devolución de llamada para obtener información adicional acerca de la red o para indicar que el tráfico use la red seleccionada.

Bluetooth de baja energía

-

Android 4.3 introdujo compatibilidad de plataforma para Bluetooth de baja energía (Bluetooth LE) en el rol central. En Android 5.0, un dispositivo Android ahora puede actuar como un dispositivo periférico Bluetooth LE. Las aplicaciones pueden utilizar esta capacidad para que otros dispositivos cercanos detecten su presencia. Por ejemplo, puedes crear aplicaciones que permiten que un dispositivo funcione como un podómetro o un monitor de estado, y comunique sus datos a otro dispositivo Bluetooth LE.

+

Android 4.3 introdujo compatibilidad de plataforma para Bluetooth de baja energía (Bluetooth LE) en el rol central. En Android 5.0, un dispositivo Android ahora puede actuar como un dispositivo periférico Bluetooth LE. Las aplicaciones pueden utilizar esta capacidad para que otros dispositivos cercanos detecten su presencia. Por ejemplo, puedes crear aplicaciones que permiten que un dispositivo funcione como un podómetro o un monitor de estado, y comunique sus datos a otro dispositivo Bluetooth LE.

Las nuevas API {@link android.bluetooth.le} permiten a sus aplicaciones transmitir anuncios, buscar respuestas y establecer conexiones con dispositivos Bluetooth LE cercanos. Para utilizar las nuevas funciones de anuncio y búsqueda, agrega el permiso {@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN} en el manifiesto. Cuando los usuarios actualizan o descargan tu aplicación desde Play Store, se les pide que concedan el siguiente permiso a tu aplicación: "Información de conexión Bluetooth: Permite que la aplicación controle Bluetooth, incluida la transmisión de información a dispositivos Bluetooth cercanos o la obtención de información sobre ellos".

Para comenzar el anuncio de Bluetooth LE a fin de que otros dispositivos puedan detectar tu aplicación, llama a {@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()} y envía una implementación de la clase {@link android.bluetooth.le.AdvertiseCallback}. El objeto de devolución de llamada recibe un informe del éxito o fracaso de la operación de anuncio.

diff --git a/docs/html-intl/intl/es/design/patterns/navigation.jd b/docs/html-intl/intl/es/design/patterns/navigation.jd index e7d73fd72fc2a..4b0523973d06d 100644 --- a/docs/html-intl/intl/es/design/patterns/navigation.jd +++ b/docs/html-intl/intl/es/design/patterns/navigation.jd @@ -137,7 +137,7 @@ evento. En la pantalla de detalles del evento, es posible navegar con los botone

Notificaciones emergentes

-

Las notificaciones emergentes omiten el panel lateral de notificaciones y aparecen directamente +

Las notificaciones emergentes omiten el panel lateral de notificaciones y aparecen directamente frente al usuario. Estas casi nunca se utilizan, y se deben reservar para ocasiones en las que es necesario proporcionar una respuesta oportuna y es necesario realizar una interrupción en el contexto del usuario. Por ejemplo, en Talk se utiliza este estilo para alertar al usuario sobre una invitación de un amigo para participar en una videocharla, ya que esta diff --git a/docs/html-intl/intl/es/design/patterns/notifications.jd b/docs/html-intl/intl/es/design/patterns/notifications.jd index bdbc77b71f467..5499e8b3d4e1c 100644 --- a/docs/html-intl/intl/es/design/patterns/notifications.jd +++ b/docs/html-intl/intl/es/design/patterns/notifications.jd @@ -56,7 +56,7 @@ Android, esta se omitirá

Nota: El diseño de las notificaciones de esta versión de -Android se diferencia +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 Notificaciones en Android 4.4 y versiones anteriores.

@@ -189,7 +189,7 @@ que aparece en la parte superior de una a los usuarios durante un período breve, con un diseño expandido que expone las posibles acciones.

Luego de este período, la notificación se retira hacia el -panel de notificaciones. Si la prioridad de una notificación +panel de notificaciones. Si la prioridad de una notificación se marca como Alta, Máxima o Pantalla completa, se obtiene una notificación emergente.

Buenos ejemplos de notificaciones emergentes

@@ -291,8 +291,8 @@ Las notificaciones de alta prioridad activan la pantalla de notificaciones emerg

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 +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.

@@ -545,7 +545,7 @@ iconos de notificaciones para

Lo que debe hacer

Utilizar el estilo de icono de notificación - adecuado para los iconos pequeños y el + adecuado para los iconos pequeños y el estilo de icono de barra de acción del diseño Material Light para los iconos de acciones.

@@ -571,7 +571,7 @@ deben ser una imagen sobre un fondo blanco o transparente.

Pulsación adecuada del LED de notificaciones

-

Muchos dispositivos con Android incluyen un LED de notificaciones, que se utiliza para mantener al +

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 MAX, HIGH o DEFAULT deben @@ -701,7 +701,7 @@ comentarios sobre tareas más extensas, como descargar un archivo o codificar un eliminar las notificaciones constantes del panel lateral de notificaciones.

Reproducción de medios

-

En Android 5.0, la pantalla de bloqueo no muestra los controles de transporte para la clase +

En Android 5.0, la pantalla de bloqueo no muestra los controles de transporte para la clase {@link android.media.RemoteControlClient} obsoleta. Sin embargo, 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 @@ -771,7 +771,7 @@ para cualquier persona que agarre el dispositivo y encienda la pantalla.

@@ -799,7 +799,7 @@ 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.
  • VISIBILITY_PRIVATE. -En la pantalla de bloqueo se muestra la información básica sobre la existencia de esta notificación, incluido +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: @@ -492,7 +492,7 @@ o simplemente centrando el icono dentro del botón transparente.
  • <uses-feature android:name="android.hardware.telephony" android:required="false" />
    -
  • En forma similar, revisa el manifiesto para detectar elementos <permission> que +
  • En forma similar, revisa el manifiesto para detectar elementos <permission> que impliquen requisitos de características de hardware que no sean adecuadas para tablets. Si encuentras esos permisos, asegúrate de declarar explícitamente un elemento @@ -735,7 +735,7 @@ o simplemente centrando el icono dentro del botón transparente.
  • distribución.

    Si la página de Sugerencias para la optimización indica problemas "Pendientes" que crees que no - corresponden a tu aplicación o afectan la calidad de la aplicación en las tablets, + corresponden a tu aplicación o afectan la calidad de la aplicación en las tablets, usa el Formulario de contacto de Diseñado para tablets» para comunicárnoslo. Revisaremos tu aplicación y actualizaremos tu página de Sugerencias para la optimización según corresponda.

    diff --git a/docs/html-intl/intl/es/distribute/googleplay/tv.jd b/docs/html-intl/intl/es/distribute/googleplay/tv.jd index e3a95bc2929db..e9deacbcfb6f9 100644 --- a/docs/html-intl/intl/es/distribute/googleplay/tv.jd +++ b/docs/html-intl/intl/es/distribute/googleplay/tv.jd @@ -132,7 +132,7 @@ page.metaDescription=Distribuye tus aplicaciones, juegos y contenido para Androi

    - 용도가 본인의 애플리케이션 안에서로 완전히 한정되어 있는 경우에는 + 용도가 본인의 애플리케이션 안에서로 완전히 한정되어 있는 경우에는 제공자가 SQLite 데이터베이스를 사용하도록 하지 않아도 됩니다.

  • - 아직 읽지 않았다면, 지금 바로 + 아직 읽지 않았다면, 지금 바로 콘텐츠 제공자 기본 정보를 읽고 제공자에 대해 자세히 알아보십시오.
  • @@ -146,8 +146,8 @@ page.title= 콘텐츠 제공자 생성
    일반적으로 사진, 오디오 또는 동영상과 같은 -파일에 들어가는 데이터입니다. 이런 파일을 애플리케이션의 비공개 -공간에 저장합니다. 제공자는 다른 애플리케이션으로부터 온 파일 요청에 응답하여 +파일에 들어가는 데이터입니다. 이런 파일을 애플리케이션의 비공개 +공간에 저장합니다. 제공자는 다른 애플리케이션으로부터 온 파일 요청에 응답하여 해당 파일로의 핸들을 제공할 수 있습니다.
    @@ -155,9 +155,9 @@ page.title= 콘텐츠 제공자 생성
    일반적으로 데이터베이스, 배열 또는 유사 구조에 들어가는 데이터입니다. - 이 데이터를 행과 열로 이루어진 테이블과 호환되는 형식으로 저장합니다. -행은 사람이나 인벤토리의 항목과 같은 엔티티를 나타냅니다. -열은 해당 엔티티에 대한 몇 가지 데이터, 예를 들어 사람 이름이나 항목 가격 등을 나타냅니다. + 이 데이터를 행과 열로 이루어진 테이블과 호환되는 형식으로 저장합니다. +행은 사람이나 인벤토리의 항목과 같은 엔티티를 나타냅니다. +열은 해당 엔티티에 대한 몇 가지 데이터, 예를 들어 사람 이름이나 항목 가격 등을 나타냅니다. 이 유형의 데이터를 저장하는 보편적인 방법은 SQLite 데이터베이스 안에 저장하는 것이지만, 모든 유형의 영구적인 저장소를 사용해도 됩니다. Android 시스템에서 사용할 수 있는 저장소 유형에 대해 자세히 알아보려면, @@ -172,11 +172,11 @@ page.title= 콘텐츠 제공자 생성 ContentProvider 클래스 구현 섹션을 참조하십시오.
  • - 제공자의 권한 문자열, 그 콘텐츠 URI 및 열 이름을 정의합니다. + 제공자의 권한 문자열, 그 콘텐츠 URI 및 열 이름을 정의합니다. 제공자 애플리케이션이 인텐트를 처리하게 하려면, 인텐트 작업과 추가 데이터 및 -플래그도 정의합니다. 데이터에 액세스하기를 원하는 애플리케이션에 요구할 권한도 -정의합니다. 이 모든 값은 별도의 계약 클래스에서 상수로 정의하는 것을 고려해보는 -것이 좋습니다. 이 클래스를 나중에 다른 개발자에게 노출할 수 있습니다. +플래그도 정의합니다. 데이터에 액세스하기를 원하는 애플리케이션에 요구할 권한도 +정의합니다. 이 모든 값은 별도의 계약 클래스에서 상수로 정의하는 것을 고려해보는 +것이 좋습니다. 이 클래스를 나중에 다른 개발자에게 노출할 수 있습니다. 콘텐츠 URI에 관한 자세한 정보는 콘텐츠 URI 설계 섹션을 참조하십시오. 인텐트에 관한 자세한 정보는 @@ -193,8 +193,8 @@ page.title= 콘텐츠 제공자 생성

    데이터 저장소 설계

    - 콘텐츠 제공자는 구조화된 형식으로 저장된 데이터로의 인터페이스입니다. -인터페이스를 생성하기 전에 우선 데이터 저장 방식부터 결정해야 합니다. + 콘텐츠 제공자는 구조화된 형식으로 저장된 데이터로의 인터페이스입니다. +인터페이스를 생성하기 전에 우선 데이터 저장 방식부터 결정해야 합니다. 데이터는 원하는 형식 아무 것으로나 저장할 수 있으며 그런 다음에 필요에 따라 해당 데이터를 읽고 쓸 인터페이스를 설계합니다.

    @@ -203,26 +203,26 @@ page.title= 콘텐츠 제공자 생성

    • Android 시스템에는 Android 자체 제공자가 테이블 지향적 데이터를 -저장하는 데 사용하는 SQLite 데이터베이스 API가 포함됩니다. +저장하는 데 사용하는 SQLite 데이터베이스 API가 포함됩니다. {@link android.database.sqlite.SQLiteOpenHelper} 클래스는 데이터베이스를 생성할 수 있게 돕고, {@link android.database.sqlite.SQLiteDatabase} 클래스는 데이터베이스 액세스를 위한 기본 클래스입니다.

      - 리포지토리를 구현하기 위해 데이터베이스를 사용하지 않아도 된다는 점을 기억하십시오. -제공자는 외부에 테이블 집합으로 나타나 관계적 데이터베이스와 비슷해 보이지만, + 리포지토리를 구현하기 위해 데이터베이스를 사용하지 않아도 된다는 점을 기억하십시오. +제공자는 외부에 테이블 집합으로 나타나 관계적 데이터베이스와 비슷해 보이지만, 이것은 제공자의 내부 구현에 필요한 것은 아닙니다.

    • 파일 데이터를 저장하는 데 있어 Android에는 다양한 파일 지향적 API가 있습니다. 파일 저장소에 관해 자세히 알아보려면 -데이터 저장소 주제를 읽어 보십시오. -음악이나 동영상 등 미디어 관련 데이터를 제공하는 제공자를 설계하는 경우, +데이터 저장소 주제를 읽어 보십시오. +음악이나 동영상 등 미디어 관련 데이터를 제공하는 제공자를 설계하는 경우, 제공자가 테이블 데이터와 파일을 조합 할 수 있습니다.
    • - 네트워크 기반 데이터를 다루는 경우, {@link java.net} 및 -{@link android.net} 내의 클래스를 사용하십시오. 네트워크 기반 데이터를 + 네트워크 기반 데이터를 다루는 경우, {@link java.net} 및 +{@link android.net} 내의 클래스를 사용하십시오. 네트워크 기반 데이터를 데이터베이스와 같은 로컬 데이터 스토어와 동기화한 다음, 해당 데이터를 테이블이나 파일로 제공할 수도 있습니다. 샘플 동기화 어댑터 샘플 애플리케이션이 이런 유형의 동기화를 보여줍니다. @@ -237,7 +237,7 @@ page.title= 콘텐츠 제공자 생성
      • 테이블 데이터는 언제나 제공자가 유지관리하는 "기본 키" 열을 -각 행의 고유한 숫자 값으로 보유하고 있어야 합니다. 이 값을 사용하여 해당 행을 다른 테이블의 +각 행의 고유한 숫자 값으로 보유하고 있어야 합니다. 이 값을 사용하여 해당 행을 다른 테이블의 관련 행에 연결시킬 수 있습니다(이를 "외래 키"로 사용). 이 열에는 어느 이름이든 사용할 수 있지만 {@link android.provider.BaseColumns#_ID BaseColumns._ID}를 사용하는 것이 가장 좋습니다. 왜냐하면 제공자 쿼리 결과를 @@ -246,8 +246,8 @@ page.title= 콘텐츠 제공자 생성
      • 비트맵 이미지나 파일 지향적 데이터의 매우 큰 조각을 제공하려면 -테이블 안에 직접 저장하기보다는 파일에 데이터를 저장한 뒤 -간접적으로 제공합니다. 이렇게 하는 경우, 제공자의 사용자들에게 데이터에 액세스하려면 +테이블 안에 직접 저장하기보다는 파일에 데이터를 저장한 뒤 +간접적으로 제공합니다. 이렇게 하는 경우, 제공자의 사용자들에게 데이터에 액세스하려면 {@link android.content.ContentResolver} 파일 메서드를 사용해야 한다고 알려야 합니다.
      • @@ -256,12 +256,12 @@ page.title= 콘텐츠 제공자 생성 프로토콜 버퍼 또는 JSON 구조를 저장할 수 있습니다.

        - BLOB를 사용하여 스키마에 종속되지 않은 테이블을 구현할 수도 있습니다. + BLOB를 사용하여 스키마에 종속되지 않은 테이블을 구현할 수도 있습니다. 이 유형의 테이블에서는, 기본 키 열, MIME 유형 열 및 하나 이상의 일반적인 열을 BLOB로 정의합니다. - -BLOB 열에 있는 데이터의 의미는 MIME 유형 열에 있는 값으로 나타냅니다. -이렇게 하면 같은 테이블에 여러 가지 행 유형을 저장할 수 있습니다. 연락처 제공자의 "데이터" 테이블 -{@link android.provider.ContactsContract.Data}가 + +BLOB 열에 있는 데이터의 의미는 MIME 유형 열에 있는 값으로 나타냅니다. +이렇게 하면 같은 테이블에 여러 가지 행 유형을 저장할 수 있습니다. 연락처 제공자의 "데이터" 테이블 +{@link android.provider.ContactsContract.Data}가 스키마에 종속되지 않은 테이블의 한 가지 예입니다.

      • @@ -269,11 +269,11 @@ BLOB 열에 있는 데이터의 의미는 MIME 유형 열에 있는 값으로

        콘텐츠 URI 설계

        - 콘텐츠 URI는 제공자에서 데이터를 식별하는 URI입니다. + 콘텐츠 URI는 제공자에서 데이터를 식별하는 URI입니다. 콘텐츠 URI에는 전체 제공자의 상징적인 이름(제공자의 권한)과 -테이블 또는 파일을 가리키는 이름(경로)이 포함됩니다. -선택 항목 ID 부분은 테이블 내의 개별적인 행을 가리킵니다. -{@link android.content.ContentProvider}의 모든 데이터 액세스 메서드는 +테이블 또는 파일을 가리키는 이름(경로)이 포함됩니다. +선택 항목 ID 부분은 테이블 내의 개별적인 행을 가리킵니다. +{@link android.content.ContentProvider}의 모든 데이터 액세스 메서드는 콘텐츠 URI를 인수로 가집니다. 이를 통해 액세스할 테이블, 행 또는 파일을 결정할 수 있습니다.

        @@ -283,9 +283,9 @@ BLOB 열에 있는 데이터의 의미는 MIME 유형 열에 있는 값으로

        권한 설계

        - 제공자에는 보통 하나의 권한이 있으며, 이것이 Android 내부 이름 역할을 합니다. + 제공자에는 보통 하나의 권한이 있으며, 이것이 Android 내부 이름 역할을 합니다. 다른 제공자와의 충돌을 피하려면, 제공자 권한의 기반으로 인터넷 도메인 소유권(역방향)을 -사용해야 합니다. 이 권장 사항은 Android 패키지 이름에도 적용되므로, +사용해야 합니다. 이 권장 사항은 Android 패키지 이름에도 적용되므로, 제공자 권한을 제공자가 들어 있는 패키지의 이름 확장자로 정의해도 됩니다. 예를 들어, Android 패키지 이름이 com.example.<appname>라면, 제공자에게 @@ -293,40 +293,40 @@ BLOB 열에 있는 데이터의 의미는 MIME 유형 열에 있는 값으로

        경로 구조 설계

        - 개발자는 보통 권한으로부터 콘텐츠 URI를 생성할 때 개별적인 테이블을 가리키는 + 개발자는 보통 권한으로부터 콘텐츠 URI를 생성할 때 개별적인 테이블을 가리키는 경로를 추가하는 방식을 사용합니다. 예를 들어, table1table2라는 테이블이 있다면, 이전 예시의 권한을 조합하여 -콘텐츠 URIcom.example.<appname>.provider/table1와 +콘텐츠 URIcom.example.<appname>.provider/table1com.example.<appname>.provider/table2를 도출합니다. - + 경로는 하나의 세그먼트에 국한되지 않으며, 경로의 각 수준에 대한 테이블이 아니어도 됩니다.

        콘텐츠 URI ID 처리

        - 규칙에 의하면, 제공자는 URI 맨 끝에서 행에 대한 ID 값이 있는 콘텐츠 URI를 허용하여 -테이블 내 하나의 행으로의 액세스를 제공합니다. 또한 규칙에 의해 제공자는 -이 ID 값을 테이블의 _ID 열에 일치시켜야 하며, + 규칙에 의하면, 제공자는 URI 맨 끝에서 행에 대한 ID 값이 있는 콘텐츠 URI를 허용하여 +테이블 내 하나의 행으로의 액세스를 제공합니다. 또한 규칙에 의해 제공자는 +이 ID 값을 테이블의 _ID 열에 일치시켜야 하며, 일치한 행에 대하여 요청된 액세스 허가를 수행해야 합니다.

        - 이 규칙은 제공자에 액세스하는 앱을 위한 공통 설계 패턴을 세우는 데 유용합니다. + 이 규칙은 제공자에 액세스하는 앱을 위한 공통 설계 패턴을 세우는 데 유용합니다. 앱이 제공자에 대한 쿼리를 수행하고 그 결과로 나온 {@link android.database.Cursor}를 {@link android.widget.ListView}에 {@link android.widget.CursorAdapter}를 사용하여 표시합니다. - {@link android.widget.CursorAdapter}의 정의에 따르면 + {@link android.widget.CursorAdapter}의 정의에 따르면 {@link android.database.Cursor} 안의 열 중 하나는 _ID여야 합니다.

        - 그러면 사용자가 데이터를 살펴보거나 수정하기 위하여 + 그러면 사용자가 데이터를 살펴보거나 수정하기 위하여 UI에서 표시된 여러 행 중 하나를 선택합니다. 앱은 {@link android.widget.ListView}를 지원하는 {@link android.database.Cursor}에서 해당하는 열을 가져오고, 해당 열에 대한 _ID 값을 가져와서 -콘텐츠 URI에 추가하고, 제공자에 액세스 요청을 전송합니다. 그런 다음 제공자는 +콘텐츠 URI에 추가하고, 제공자에 액세스 요청을 전송합니다. 그런 다음 제공자는 사용자가 선택한 바로 그 행에 대해 쿼리 또는 수정 작업을 수행할 수 있습니다.

        콘텐츠 URI 패턴

        - 수신되는 콘텐츠 URI에 대해 어떤 조치를 취할지 선택하는 데 도움이 되도록 하기 위해 제공자 API에 -편의 클래스 {@link android.content.UriMatcher}가 -포함되어 있습니다. 이는 콘텐츠 URI "패턴"을 정수값으로 매핑합니다. 이 정수값은 특정 패턴에 일치하는 + 수신되는 콘텐츠 URI에 대해 어떤 조치를 취할지 선택하는 데 도움이 되도록 하기 위해 제공자 API에 +편의 클래스 {@link android.content.UriMatcher}가 +포함되어 있습니다. 이는 콘텐츠 URI "패턴"을 정수값으로 매핑합니다. 이 정수값은 특정 패턴에 일치하는 콘텐츠 URI 또는 여러 URI에 대해 원하는 작업을 선택하는 데 switch 문에서 사용할 수 있습니다.

        @@ -341,8 +341,8 @@ UI에서 표시된 여러 행 중 하나를 선택합니다. 앱은 {@link andro

      - 콘텐츠 URI 처리의 설계와 코딩에 대한 예시로서 임의의 제공자를 들어 보겠습니다. -이 제공자에는 권한 com.example.app.provider가 있고 + 콘텐츠 URI 처리의 설계와 코딩에 대한 예시로서 임의의 제공자를 들어 보겠습니다. +이 제공자에는 권한 com.example.app.provider가 있고 이 권한이 테이블을 가리키는 다음 콘텐츠 URI를 인식합니다.

        @@ -350,11 +350,11 @@ UI에서 표시된 여러 행 중 하나를 선택합니다. 앱은 {@link andro content://com.example.app.provider/table1: table1이라는 테이블입니다.
      • - content://com.example.app.provider/table2/dataset1: + content://com.example.app.provider/table2/dataset1: dataset1이라는 테이블입니다.
      • - content://com.example.app.provider/table2/dataset2: + content://com.example.app.provider/table2/dataset2: dataset2라는 테이블입니다.
      • @@ -363,7 +363,7 @@ UI에서 표시된 여러 행 중 하나를 선택합니다. 앱은 {@link andro

      제공자는 추가된 행 ID가 있으면 이런 콘텐츠 URI도 인식합니다. -예를 들어, table3에서 1이 식별한 행에 대한 +예를 들어, table3에서 1이 식별한 행에 대한 content://com.example.app.provider/table3/1이 이에 해당됩니다.

      @@ -385,7 +385,7 @@ UI에서 표시된 여러 행 중 하나를 선택합니다. 앱은 {@link andro table3에 대한 콘텐츠 URI와 일치하지 않습니다.

  • - content://com.example.app.provider/table3/#: + content://com.example.app.provider/table3/#: table3의 단일 행에 대한 콘텐츠 URI와 일치합니다. 예를 들어, 6이 식별한 행에 대한 content://com.example.app.provider/table3/6이 이에 해당됩니다. @@ -393,8 +393,8 @@ UI에서 표시된 여러 행 중 하나를 선택합니다. 앱은 {@link andro

    다음 코드 조각은 {@link android.content.UriMatcher} 작업에서 메서드의 작용 원리를 나타낸 것입니다. - 이 코드는 테이블에 대한 콘텐츠 URI 패턴 content://<authority>/<path>와 -단일 행에 대한 콘텐츠 URI 패턴 content://<authority>/<path>/<id>를 사용하여 + 이 코드는 테이블에 대한 콘텐츠 URI 패턴 content://<authority>/<path>와 +단일 행에 대한 콘텐츠 URI 패턴 content://<authority>/<path>/<id>를 사용하여 단일 행에 대한 URI와 전체 테이블에 대한 URI를 서로 다르게 처리합니다.

    @@ -468,7 +468,7 @@ public class ExampleProvider extends ContentProvider { }

    - 또 다른 클래스, {@link android.content.ContentUris}가 + 또 다른 클래스, {@link android.content.ContentUris}가 콘텐츠 URI의 id 부분을 다루기 위한 편의 메서드를 제공합니다. 클래스 {@link android.net.Uri}와 {@link android.net.Uri.Builder}에는 기존 {@link android.net.Uri} 개체를 구문 분석하고 새로운 개체를 구축하기 위한 편의 메서드가 포함되어 있습니다. @@ -478,15 +478,15 @@ public class ExampleProvider extends ContentProvider {

    ContentProvider 클래스 구현

    {@link android.content.ContentProvider} 인스턴스는 -다른 애플리케이션으로부터의 요청을 처리하여 구조화된 데이터 세트로의 액세스를 관리합니다. -모든 형태의 액세서가 궁극적으로 {@link android.content.ContentResolver}를 호출하며, +다른 애플리케이션으로부터의 요청을 처리하여 구조화된 데이터 세트로의 액세스를 관리합니다. +모든 형태의 액세서가 궁극적으로 {@link android.content.ContentResolver}를 호출하며, 그러면 이것이 액세스 권한을 얻기 위해 구체적인 {@link android.content.ContentProvider} 메서드를 호출합니다.

    필수 메서드

    - 추상 클래스 {@link android.content.ContentProvider}는 -개발자가 나름의 구체적인 하위 클래스의 일부분으로 구현해야만 하는 여섯 가지 추상 메서드를 정의합니다. 이와 같은 메서드는 모두 -({@link android.content.ContentProvider#onCreate() onCreate()}는 예외) + 추상 클래스 {@link android.content.ContentProvider}는 +개발자가 나름의 구체적인 하위 클래스의 일부분으로 구현해야만 하는 여섯 가지 추상 메서드를 정의합니다. 이와 같은 메서드는 모두 +({@link android.content.ContentProvider#onCreate() onCreate()}는 예외) 콘텐츠 제공자에 액세스하려 시도 중인 클라이언트 애플리케이션이 호출합니다.

    @@ -503,8 +503,8 @@ query()} {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()}
    - 제공자에 새로운 행을 삽입합니다. 인수를 사용하여 대상 테이블을 선택하고 -사용할 열 값을 가져옵니다. + 제공자에 새로운 행을 삽입합니다. 인수를 사용하여 대상 테이블을 선택하고 +사용할 열 값을 가져옵니다. 새로 삽입된 행에 대한 콘텐츠 URI를 반환합니다.
    @@ -512,7 +512,7 @@ query()} update()}
    - 제공자 내의 기존 행을 업데이트합니다. 인수를 사용하여 + 제공자 내의 기존 행을 업데이트합니다. 인수를 사용하여 업데이트할 테이블과 행을 선택하고 업데이트한 열 값을 가져옵니다. 업데이트한 행 개수를 반환합니다.
    @@ -526,20 +526,20 @@ update()} {@link android.content.ContentProvider#getType(Uri) getType()}
    - 콘텐츠 URI에 상응하는 MIME 유형을 반환합니다. 이 메서드는 + 콘텐츠 URI에 상응하는 MIME 유형을 반환합니다. 이 메서드는 콘텐츠 제공자 MIME 유형 섹션에 더 자세하게 설명되어 있습니다.
    {@link android.content.ContentProvider#onCreate() onCreate()}
    - 제공자를 초기화합니다. Android 시스템은 제공자를 생성한 직후 -이 메서드를 호출합니다. + 제공자를 초기화합니다. Android 시스템은 제공자를 생성한 직후 +이 메서드를 호출합니다. {@link android.content.ContentResolver} 개체가 제공자에 액세스하려고 시도할 때까지는 제공자가 생성된 것이 아니라는 점을 유의하십시오.

    - 이와 같은 메서드에는 동일하게 이름 붙여진 + 이와 같은 메서드에는 동일하게 이름 붙여진 {@link android.content.ContentResolver} 메서드와 같은 서명이 있다는 것을 눈여겨 보십시오.

    @@ -548,8 +548,8 @@ update()}

    query() 메서드 구현

    - + {@link android.content.ContentProvider#query(Uri, String[], String, String[], String) ContentProvider.query()} 메서드는 {@link android.database.Cursor} 개체를 반환해야 하고, 그렇지 못할 경우 {@link java.lang.Exception}을 발생시킵니다. SQLite 데이터베이스를 데이터 저장소로 사용하는 경우, @@ -587,7 +587,7 @@ ContentProvider.query()} 메서드는 {@link android.database.Cursor} 개체를

    Android 시스템이 프로세스 경계를 가로질러 {@link java.lang.Exception}을 - 통신으로 전달할 수 있어야 한다는 점을 유의하십시오. Android가 이 작업을 할 수 있는 경우는 + 통신으로 전달할 수 있어야 한다는 점을 유의하십시오. Android가 이 작업을 할 수 있는 경우는 쿼리 오류 처리에 유용할 수 있는 다음과 같은 예외에 해당될 때입니다.

    - 예를 들어 어떤 제공자의 권한이 -com.example.app.provider이고, 이것이 + 예를 들어 어떤 제공자의 권한이 +com.example.app.provider이고, 이것이 table1이라는 테이블을 노출하는 경우, table1의 여러 행에 대한 MIME 유형은 다음과 같습니다.

    @@ -833,8 +833,8 @@ vnd.android.cursor.item/vnd.com.example.provider.table1
     

    제공자가 파일을 제공하는 경우, {@link android.content.ContentProvider#getStreamTypes(Uri, String) getStreamTypes()}를 구현합니다. - 이 메서드는 제공자가 주어진 콘텐츠 URI에 대해 반환할 수 있는 파일에 대한 MIME 유형의 {@link java.lang.String} 배열을 반환합니다. -제공하는 MIME 유형을 MIME 유형 필터 인수 기준으로 필터링해야 + 이 메서드는 제공자가 주어진 콘텐츠 URI에 대해 반환할 수 있는 파일에 대한 MIME 유형의 {@link java.lang.String} 배열을 반환합니다. +제공하는 MIME 유형을 MIME 유형 필터 인수 기준으로 필터링해야 클라이언트가 처리하고자 하는 MIME 유형만 반환할 수 있습니다.

    @@ -850,16 +850,16 @@ ContentProvider.getStreamTypes()} 메서드가 다음과 같은 배열을 반환 { "image/jpeg", "image/png", "image/gif"}

    - 앱이 .jpg 파일에만 관심이 있는 경우에는 + 앱이 .jpg 파일에만 관심이 있는 경우에는 필터 문자열 *\/jpeg으로 {@link android.content.ContentResolver#getStreamTypes(Uri, String) - ContentResolver.getStreamTypes()}를 호출할 수 있습니다. 그러면 + ContentResolver.getStreamTypes()}를 호출할 수 있습니다. 그러면 {@link android.content.ContentProvider#getStreamTypes(Uri, String) ContentProvider.getStreamTypes()}가 다음과 같이 반환하는 것이 정상입니다.

     {"image/jpeg"}
     

    - 제공자가 필터 문자열에서 요청한 MIME 유형 중 제공하는 것이 없는 경우, + 제공자가 필터 문자열에서 요청한 MIME 유형 중 제공하는 것이 없는 경우, {@link android.content.ContentProvider#getStreamTypes(Uri, String) getStreamTypes()}가 null을 반환하는 것이 정상입니다.

    @@ -868,76 +868,76 @@ ContentProvider.getStreamTypes()} 메서드가 다음과 같은 배열을 반환

    계약 클래스 구현

    - 계약 클래스는 public final 클래스로, 이 안에 URI, 열 이름, MIME 유형의 -상수 정의 및 제공자에 관련된 다른 메타 데이터가 들어 있습니다. + 계약 클래스는 public final 클래스로, 이 안에 URI, 열 이름, MIME 유형의 +상수 정의 및 제공자에 관련된 다른 메타 데이터가 들어 있습니다. 이 클래스는 URI, 열 이름 등의 실제 값에 변경된 내용이 있더라도 - 제공자에 올바르게 액세스할 수 있도록 보장하여 제공자와 + 제공자에 올바르게 액세스할 수 있도록 보장하여 제공자와 다른 애플리케이션 사이의 계약을 확립합니다.

    - 계약 클래스가 개발자에게 유용한 이유는 또 있습니다. 이 클래스는 보통 자신의 상수 이름으로 -니모닉 이름을 가지기 때문에 개발자가 열 이름 또는 URI에 잘못된 값을 사용할 가능성이 덜합니다. -이것도 클래스의 일종이기 때문에 Javadoc 문서를 포함할 수 있습니다. + 계약 클래스가 개발자에게 유용한 이유는 또 있습니다. 이 클래스는 보통 자신의 상수 이름으로 +니모닉 이름을 가지기 때문에 개발자가 열 이름 또는 URI에 잘못된 값을 사용할 가능성이 덜합니다. +이것도 클래스의 일종이기 때문에 Javadoc 문서를 포함할 수 있습니다. Eclipse와 같은 통합 개발 환경은 계약 클래스의 상수 이름을 자동 완성하고 해당 상수에 대한 Javadoc을 표시할 수 있습니다.

    - 개발자가 애플리케이션에서 계약 클래스의 클래스 파일에 액세스할 수는 없지만 + 개발자가 애플리케이션에서 계약 클래스의 클래스 파일에 액세스할 수는 없지만 여러분이 제공하는 .jar 파일에서 이를 애플리케이션 안으로 정적으로 컴파일링할 수 있습니다.

    - {@link android.provider.ContactsContract} 클래스와 + {@link android.provider.ContactsContract} 클래스와 이에 중첩된 클래스가 계약 클래스의 예시입니다.

    콘텐츠 제공자 권한 구현

    Android 시스템의 모든 측면에 대한 권한과 액세스는 보안 및 권한 주제에 설명되어 있습니다. - 데이터 저장소 주제에서도 + 데이터 저장소 주제에서도 다양한 유형의 저장소에 적용되는 보안 및 권한을 설명하고 있습니다. 간략히 말해 요점은 다음과 같습니다.

    - 데이터로의 액세스를 제어하기 위해 콘텐츠 제공자 권한을 쓰고자 하는 경우, -데이터를 내부 파일, SQLite 데이터베이스 또는 "클라우드"(예: 원격 서버) 안의 + 데이터로의 액세스를 제어하기 위해 콘텐츠 제공자 권한을 쓰고자 하는 경우, +데이터를 내부 파일, SQLite 데이터베이스 또는 "클라우드"(예: 원격 서버) 안의 내부 파일로 저장해야 하고, 파일과 데이터베이스를 애플리케이션만의 비공개로 유지해야 합니다.

    권한 구현

    - 기본 데이터가 비공개라고 하더라도 모든 애플리케이션이 제공자를 읽고 제공자에 쓸 수 있습니다. + 기본 데이터가 비공개라고 하더라도 모든 애플리케이션이 제공자를 읽고 제공자에 쓸 수 있습니다. 기본적으로 제공자에는 권한이 설정되어 있지 않기 때문입니다. 이를 변경하려면, <provider> 요소의 속성이나 하위 요소를 사용하여 -매니페스트 파일에 있는 제공자의 권한을 설정합니다. 권한은 제공자 전체에 적용되도록 설정할 수도 있고, +매니페스트 파일에 있는 제공자의 권한을 설정합니다. 권한은 제공자 전체에 적용되도록 설정할 수도 있고, 특정 테이블에, 또는 심지어 특정 레코드에 적용되게 할 수도 있고 세 가지 모두를 택할 수도 있습니다.

    - 제공자에 대한 권한은 매니페스트 파일에 있는 하나 이상의 + 제공자에 대한 권한은 매니페스트 파일에 있는 하나 이상의 - <permission> 요소로 정의합니다. + <permission> 요소로 정의합니다. 제공자에 고유한 권한을 설정하려면 android:name 속성에 Java 스타일 범위를 사용합니다. 예를 들어 읽기 권한의 이름을 @@ -945,7 +945,7 @@ Eclipse와 같은 통합 개발 환경은 계약 클래스의 상수 이름을

    - 다음 목록은 제공자 권한의 범위를 설명한 것입니다. + 다음 목록은 제공자 권한의 범위를 설명한 것입니다. 제공자 전체에 적용되는 권한부터 시작하여 점차 세분화된 권한이 됩니다. 보다 세부화된 권한이 범위가 큰 것보다 우선합니다.

    @@ -954,9 +954,9 @@ Eclipse와 같은 통합 개발 환경은 계약 클래스의 상수 이름을 단일 읽기-쓰기 제공자 수준 권한
    - 제공자 전체로의 읽기와 쓰기 액세스 양쪽 모두를 제어하는 하나의 권한으로, + 제공자 전체로의 읽기와 쓰기 액세스 양쪽 모두를 제어하는 하나의 권한으로, - <provider> 요소의 + <provider> 요소의 android:permission 속성으로 지정됩니다.
    @@ -978,14 +978,14 @@ Eclipse와 같은 통합 개발 환경은 계약 클래스의 상수 이름을 경로 수준 권한
    - 제공자의 콘텐츠 URI에 대한 읽기, 쓰기 또는 읽기/쓰기 권한입니다. 제어하고자 하는 각 URI를 직접 지정하되, -이때 + 제공자의 콘텐츠 URI에 대한 읽기, 쓰기 또는 읽기/쓰기 권한입니다. 제어하고자 하는 각 URI를 직접 지정하되, +이때 - <provider> 요소의 + <provider> 요소의 - <path-permission> 하위 요소를 사용합니다. 지정하는 콘텐츠 URI마다 -읽기/쓰기 권한, 읽기 권한 또는 쓰기 권한을 하나씩 지정하거나 셋 모두를 지정할 수 있습니다. -읽기 및 쓰기 권한이 읽기/쓰기 권한보다 우선합니다. + <path-permission> 하위 요소를 사용합니다. 지정하는 콘텐츠 URI마다 +읽기/쓰기 권한, 읽기 권한 또는 쓰기 권한을 하나씩 지정하거나 셋 모두를 지정할 수 있습니다. +읽기 및 쓰기 권한이 읽기/쓰기 권한보다 우선합니다. 또한, 경로 수준 권한이 제공자 수준 권한보다 우선합니다.
    @@ -993,18 +993,18 @@ Eclipse와 같은 통합 개발 환경은 계약 클래스의 상수 이름을
    애플리케이션에 임시 액세스를 허용하는 권한 수준입니다. -해당 애플리케이션에 일반적으로 요구되는 권한이 없더라도 무관합니다. +해당 애플리케이션에 일반적으로 요구되는 권한이 없더라도 무관합니다. 임시 액세스 기능은 매니페스트에서 요청해야 하는 -권한과 애플리케이션 개수를 줄여줍니다. 임시 권한을 사용하는 경우, -제공자에 대하여 "영구" 권한을 필요로하는 애플리케이션은 +권한과 애플리케이션 개수를 줄여줍니다. 임시 권한을 사용하는 경우, +제공자에 대하여 "영구" 권한을 필요로하는 애플리케이션은 모든 데이터에 지속적으로 액세스하는 것들뿐입니다.

    - 이메일 제공자와 앱을 구현할 때 필요한 권한을 예로 들어 보겠습니다. -외부 이미지 뷰어 애플리케이션으로 하여금 제공자에서 보낸 사진 첨부 파일을 -표시하도록 허용하고자 한다고 가정합니다. 권한을 요구하지 않고 이미지 뷰어에 필수 액세스를 부여하려면, -사진에 대한 콘텐츠 URI에 해단되는 임시 권한을 설정하십시오. + 이메일 제공자와 앱을 구현할 때 필요한 권한을 예로 들어 보겠습니다. +외부 이미지 뷰어 애플리케이션으로 하여금 제공자에서 보낸 사진 첨부 파일을 +표시하도록 허용하고자 한다고 가정합니다. 권한을 요구하지 않고 이미지 뷰어에 필수 액세스를 부여하려면, +사진에 대한 콘텐츠 URI에 해단되는 임시 권한을 설정하십시오. 사용자가 사진을 표시하기를 원할 때 앱이 사진의 콘텐츠 URI와 권한 플래그를 포함하는 인텐트를 -이미지 뷰어에 보내도록 이메일 앱을 설계합니다. 그러면 해당 이미지 뷰어가 +이미지 뷰어에 보내도록 이메일 앱을 설계합니다. 그러면 해당 이미지 뷰어가 이메일 제공자에 사진 검색을 쿼리할 수 있으며, 이 뷰어에 제공자에 대한 정상적인 읽기 권한이 없더라도 무방합니다.

    @@ -1017,29 +1017,29 @@ Eclipse와 같은 통합 개발 환경은 계약 클래스의 상수 이름을 <grant-uri-permission> 하위 요소를 - <provider> 요소에 추가하면 됩니다. 임시 권한을 사용하는 경우, + <provider> 요소에 추가하면 됩니다. 임시 권한을 사용하는 경우, 제공자에서 콘텐츠 URI에 대한 지원을 제거할 때마다 {@link android.content.Context#revokeUriPermission(Uri, int) - Context.revokeUriPermission()}을 호출해야 합니다. + Context.revokeUriPermission()}을 호출해야 합니다. 그러면 콘텐츠 URI가 임시 권한과 연관됩니다.

    속성의 값에 따라 제공자에 액세스 가능한 정도가 결정됩니다. - 속성이 true로 설정되어 있는 경우라면 -시스템이 제공자 전체에 임시 권한을 허용하며, 제공자 수준 또는 + 속성이 true로 설정되어 있는 경우라면 +시스템이 제공자 전체에 임시 권한을 허용하며, 제공자 수준 또는 경로 수준 권한에서 요구하는 다른 모든 권한을 재정의합니다.

    - 이 플래그가 false로 설정되면, 반드시 + 이 플래그가 false로 설정되면, 반드시 <grant-uri-permission> 하위 요소를 - <provider> 요소에 추가해야 합니다. 각 하위 요소는 임시 권한을 허용한 + <provider> 요소에 추가해야 합니다. 각 하위 요소는 임시 권한을 허용한 콘텐츠 URI(하나 또는 여러 개)를 나타냅니다.

    애플리케이션에 임시 액세스를 위임하려면, 인텐트에 {@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} 또는 -{@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} 플래그, 또는 둘 모두가 들어 있어야 합니다. 이들은 +{@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} 플래그, 또는 둘 모두가 들어 있어야 합니다. 이들은 {@link android.content.Intent#setFlags(int) setFlags()} 메서드로 설정됩니다.

    @@ -1087,7 +1087,7 @@ android:authorities}) 권한

    - 제공자의 데이터에 액세스하기 위해 다른 애플리케이션이 + 제공자의 데이터에 액세스하기 위해 다른 애플리케이션이 반드시 가지고 있어야 하는 권한을 나타내는 속성입니다.

    - 각종 권한과 그에 상응하는 속성은 + 각종 권한과 그에 상응하는 속성은 콘텐츠 제공자 권한 구현 섹션에 자세히 설명되어 있습니다.

    @@ -1117,7 +1117,7 @@ android:authorities}) 시작 및 제어 속성
    - 이와 같은 속성은 Android 시스템이 제공자를 시작하는 방법과 시점, + 이와 같은 속성은 Android 시스템이 제공자를 시작하는 방법과 시점, 제공자의 프로세스 특징과 기타 런타임 설정 등을 결정합니다. @@ -1165,7 +1165,7 @@ android:authorities})
  • android:icon: 제공자의 아이콘이 들어 있는 드로어블 리소스입니다. - 이 아이콘은 + 이 아이콘은 설정 > > 모두에 있는 앱 목록에서 제공자의 레이블 옆에 표시됩니다.
  • @@ -1187,28 +1187,28 @@ android:authorities})

    인텐트 및 데이터 액세스

    애플리케이션이 콘텐츠 제공자에 간접적으로 액세스하려면 {@link android.content.Intent}를 사용하면 됩니다. - 이 애플리케이션은 {@link android.content.ContentResolver} 또는 -{@link android.content.ContentProvider}의 메서드 중 어느 하나도 호출하지 않습니다. -대신, 액티비티를 시작하는 인텐트를 전송합니다. 이 인텐트는 제공자가 소유한 애플리케이션의 일부인 경우가 많습니다. -대상 액티비티가 데이터를 자체 UI에서 검색하고 표시하는 역할을 맡습니다. + 이 애플리케이션은 {@link android.content.ContentResolver} 또는 +{@link android.content.ContentProvider}의 메서드 중 어느 하나도 호출하지 않습니다. +대신, 액티비티를 시작하는 인텐트를 전송합니다. 이 인텐트는 제공자가 소유한 애플리케이션의 일부인 경우가 많습니다. +대상 액티비티가 데이터를 자체 UI에서 검색하고 표시하는 역할을 맡습니다. 인텐트의 동작에 따라 대상 액티비티가 사용자에게 프롬프트를 표시하여 제공자의 데이터를 수정하도록 할 수도 있습니다. 인텐트에는 대상 액티비티가 UI에 표시하는 "추가" 데이터가 들어 있을 수도 있습니다. -그러면 사용자에게 이 데이터를 변경할 수 있는 옵션이 주어지고, 그런 다음 이를 사용하여 +그러면 사용자에게 이 데이터를 변경할 수 있는 옵션이 주어지고, 그런 다음 이를 사용하여 제공자 내의 데이터를 수정할 수 있습니다.

    - 데이터 무결성을 보장하는 데 유용한 것을 원하면 인텐트 액세스를 사용하는 것이 좋습니다. -엄격하게 정의된 비즈니스 논리에 따라 데이터가 삽입, 업데이트되고 삭제되는 것이 제공자를 크게 좌우할 수도 있습니다. -이런 경우에 해당되면, 다른 애플리케이션에 데이터를 직접 수정하도록 허용하면 데이터가 잘못되는 + 데이터 무결성을 보장하는 데 유용한 것을 원하면 인텐트 액세스를 사용하는 것이 좋습니다. +엄격하게 정의된 비즈니스 논리에 따라 데이터가 삽입, 업데이트되고 삭제되는 것이 제공자를 크게 좌우할 수도 있습니다. +이런 경우에 해당되면, 다른 애플리케이션에 데이터를 직접 수정하도록 허용하면 데이터가 잘못되는 결과를 초래할 수 있습니다. 개발자들에게 인텐트 액세스 사용을 허용하려면, 그 내용을 철저히 기록해두어야 합니다. - 개발자들에게 자기 애플리케이션의 UI를 사용한 인텐트 액세스가 + 개발자들에게 자기 애플리케이션의 UI를 사용한 인텐트 액세스가 코드로 데이터를 수정하려 시도하는 것보다 나은 이유를 설명해주십시오.

    제공자의 데이터를 수정하고자 하는 수신되는 인텐트 처리도 다른 인텐트 처리와 다를 바가 없습니다. - 인텐트 사용에 대한 자세한 내용은 + 인텐트 사용에 대한 자세한 내용은 인텐트 및 인텐트 필터 주제를 읽으면 확인할 수 있습니다.

    diff --git a/docs/html-intl/intl/ko/guide/topics/providers/content-providers.jd b/docs/html-intl/intl/ko/guide/topics/providers/content-providers.jd index ce98840e16db4..8671f7b71f91b 100644 --- a/docs/html-intl/intl/ko/guide/topics/providers/content-providers.jd +++ b/docs/html-intl/intl/ko/guide/topics/providers/content-providers.jd @@ -47,31 +47,31 @@ page.title=콘텐츠 제공자

    - 콘텐츠 제공자는 구조화된 데이터 세트로의 액세스를 관리합니다. -데이터를 캡슐화하여 데이터 보안을 정의하는 데 필요한 메커니즘을 제공하기도 합니다. + 콘텐츠 제공자는 구조화된 데이터 세트로의 액세스를 관리합니다. +데이터를 캡슐화하여 데이터 보안을 정의하는 데 필요한 메커니즘을 제공하기도 합니다. 콘텐츠 제공자는 한 프로세스의 데이터에 다른 프로세스에서 실행 중인 코드를 연결하는 표준 인터페이스입니다.

    - 콘텐츠 제공자 내의 데이터에 액세스하고자 하는 경우, + 콘텐츠 제공자 내의 데이터에 액세스하고자 하는 경우, 애플리케이션의 {@link android.content.Context}에 있는 {@link android.content.ContentResolver} 개체를 사용하여 클라이언트로서 제공자와 통신을 주고받으면 됩니다. - {@link android.content.ContentResolver} 개체가 제공자 개체와 통신하며, 이 개체는 -{@link android.content.ContentProvider}를 구현하는 클래스의 인스턴스입니다. + {@link android.content.ContentResolver} 개체가 제공자 개체와 통신하며, 이 개체는 +{@link android.content.ContentProvider}를 구현하는 클래스의 인스턴스입니다. 제공자 개체가 클라이언트로부터 데이터 요청을 받아 요청된 작업을 수행하며 결과를 반환합니다.

    데이터를 다른 애플리케이션과 공유할 생각이 없으면 나름의 제공자를 개발하지 않아도 됩니다. 그러나, 자체 애플리케이션에서 사용자 지정 검색 제안을 제공하려면 나름의 제공자가 꼭 필요합니다. - 또한, 복잡한 데이터나 파일을 자신의 애플리케이션에서 다른 애플리케이션으로 복사하여 붙여넣고자 하는 경우에도 + 또한, 복잡한 데이터나 파일을 자신의 애플리케이션에서 다른 애플리케이션으로 복사하여 붙여넣고자 하는 경우에도 나름의 제공자가 필요합니다.

    - Android 자체에 오디오, 동영상, 이미지 및 개인 연락처 정보 등의 데이터를 관리하는 콘텐츠 제공자가 -포함되어 있습니다. 그중 몇 가지를 목록으로 나열한 것을 + Android 자체에 오디오, 동영상, 이미지 및 개인 연락처 정보 등의 데이터를 관리하는 콘텐츠 제공자가 +포함되어 있습니다. 그중 몇 가지를 목록으로 나열한 것을 android.provider - 패키지에 대한 참조 문서에서 확인할 수 있습니다. 이와 같은 제공자는 몇 가지 제약이 있지만, + 패키지에 대한 참조 문서에서 확인할 수 있습니다. 이와 같은 제공자는 몇 가지 제약이 있지만, 어느 Android 애플리케이션에나 액세스할 수 있습니다.

    다음 주제에서는 콘텐츠 제공자에 대해 좀 더 자세히 설명합니다. diff --git a/docs/html-intl/intl/ko/guide/topics/providers/document-provider.jd b/docs/html-intl/intl/ko/guide/topics/providers/document-provider.jd index e356e22d17c9b..665a72a755cfe 100644 --- a/docs/html-intl/intl/ko/guide/topics/providers/document-provider.jd +++ b/docs/html-intl/intl/ko/guide/topics/providers/document-provider.jd @@ -75,96 +75,96 @@ StorageClient

  • -

    Android 4.4(API 레벨 19)에서는 저장소 액세스 프레임워크(SAF)를 처음 도입하게 되었습니다. SAF는 -사용자가 선호하는 문서 저장소 제공자 전체를 걸쳐 문서, 이미지 및 각종 다른 파일을 -탐색하고 여는 작업을 간편하게 만들어줍니다. 표준형의, 사용하기 쉬운 UI로 +

    Android 4.4(API 레벨 19)에서는 저장소 액세스 프레임워크(SAF)를 처음 도입하게 되었습니다. SAF는 +사용자가 선호하는 문서 저장소 제공자 전체를 걸쳐 문서, 이미지 및 각종 다른 파일을 +탐색하고 여는 작업을 간편하게 만들어줍니다. 표준형의, 사용하기 쉬운 UI로 사용자가 각종 앱과 제공자에 걸쳐 일관된 방식으로 파일을 탐색하고 최근 내용에 액세스할 수 있게 해줍니다.

    -

    클라우드 또는 로컬 저장소 서비스가 이 에코시스템에 참가하려면 자신의 서비스를 캡슐화하는 -{@link android.provider.DocumentsProvider}를 구현하면 됩니다. -제공자의 문서에 액세스해야 하는 클라이언트 앱의 경우 단 몇 줄의 코드만으로 +

    클라우드 또는 로컬 저장소 서비스가 이 에코시스템에 참가하려면 자신의 서비스를 캡슐화하는 +{@link android.provider.DocumentsProvider}를 구현하면 됩니다. +제공자의 문서에 액세스해야 하는 클라이언트 앱의 경우 단 몇 줄의 코드만으로 SAF와 통합할 수 있습니다.

    SAF에는 다음과 같은 항목이 포함됩니다.

    SAF가 제공하는 기능을 몇 가지 예로 들면 다음과 같습니다.

    개요

    -

    SAF는 {@link android.provider.DocumentsProvider} 클래스의 -하위 클래스인 콘텐츠 제공자를 중심으로 둘러싸고 있습니다. 데이터는 문서 제공자 내에서 일반적인 파일 계층으로 +

    SAF는 {@link android.provider.DocumentsProvider} 클래스의 +하위 클래스인 콘텐츠 제공자를 중심으로 둘러싸고 있습니다. 데이터는 문서 제공자 내에서 일반적인 파일 계층으로 구조화됩니다.

    data model

    -

    그림 1. 문서 제공자 데이터 모델입니다. 루트 하나가 하나의 문서를 가리키며, +

    그림 1. 문서 제공자 데이터 모델입니다. 루트 하나가 하나의 문서를 가리키며, 이는 다시 트리 전체의 팬아웃을 시작합니다.

    다음 내용을 참고하십시오.

    제어 흐름

    -

    위에서 언급한 바와 같이, 문서 제공자 데이터 모델은 일반적인 -파일 계층을 기반으로 합니다. 그러나, 데이터를 물리적으로 저장하는 방식은 마음대로 선택할 수 있습니다. 다만 -{@link android.provider.DocumentsProvider} API를 통해 액세스할 수 있기만 하면 됩니다. +

    위에서 언급한 바와 같이, 문서 제공자 데이터 모델은 일반적인 +파일 계층을 기반으로 합니다. 그러나, 데이터를 물리적으로 저장하는 방식은 마음대로 선택할 수 있습니다. 다만 +{@link android.provider.DocumentsProvider} API를 통해 액세스할 수 있기만 하면 됩니다. 예를 들어, 데이터를 저장하기 위해 태그 기반 클라우드 저장소를 사용해도 됩니다.

    -

    그림 2는 사진 앱이 SAF를 사용하여 저장된 데이터에 액세스할 수 있는 방법을 +

    그림 2는 사진 앱이 SAF를 사용하여 저장된 데이터에 액세스할 수 있는 방법을 예시로 나타낸 것입니다.

    app

    @@ -174,31 +174,31 @@ Android 플랫폼에는 내장된 문서 제공자가 여러 개 있습니다. -

    그림 3은 이미지를 검색 중인 사용자가 Google Drive 계정을 선택한 +

    그림 3은 이미지를 검색 중인 사용자가 Google Drive 계정을 선택한 선택기를 나타낸 것입니다.

    picker

    그림 3. 선택기

    -

    사용자가 Google Drive를 선택하면 이미지가 그림 4에 나타난 것처럼 -표시됩니다. 그때부터 사용자는 제공자와 클라이언트 앱이 지원하는 방식이라면 어떤 식으로든 +

    사용자가 Google Drive를 선택하면 이미지가 그림 4에 나타난 것처럼 +표시됩니다. 그때부터 사용자는 제공자와 클라이언트 앱이 지원하는 방식이라면 어떤 식으로든 이들 이미지와 상호 작용할 수 있게 됩니다.

    picker

    @@ -207,45 +207,45 @@ Google Drive 제공자, USB 제공자와 클라우드 제공자를 나타낸 것

    클라이언트 앱 작성

    -

    Android 4.3 이하에서는 앱이 또 다른 앱에서 파일을 검색할 수 있도록 하려면 +

    Android 4.3 이하에서는 앱이 또 다른 앱에서 파일을 검색할 수 있도록 하려면 {@link android.content.Intent#ACTION_PICK} - 또는 {@link android.content.Intent#ACTION_GET_CONTENT}와 같은 인텐트를 호출해야만 했습니다. 그런 다음 -파일을 선택할 앱을 하나 선택하고, 선택한 앱이 사용자 인터페이스를 제공하여야 사용자가 + 또는 {@link android.content.Intent#ACTION_GET_CONTENT}와 같은 인텐트를 호출해야만 했습니다. 그런 다음 +파일을 선택할 앱을 하나 선택하고, 선택한 앱이 사용자 인터페이스를 제공하여야 사용자가 이용 가능한 파일 중에서 탐색하고 선택할 수 있었습니다.

    -

    Android 4.4 이상에는 -{@link android.content.Intent#ACTION_OPEN_DOCUMENT} 인텐트를 사용할 수 있다는 추가 옵션이 있습니다. -이는 시스템이 제어하는 선택기를 표시하여 사용자가 다른 앱에서 이용할 수 있게 만든 파일을 -모두 탐색할 수 있게 해줍니다. 이 하나의 UI로부터 +

    Android 4.4 이상에는 +{@link android.content.Intent#ACTION_OPEN_DOCUMENT} 인텐트를 사용할 수 있다는 추가 옵션이 있습니다. +이는 시스템이 제어하는 선택기를 표시하여 사용자가 다른 앱에서 이용할 수 있게 만든 파일을 +모두 탐색할 수 있게 해줍니다. 이 하나의 UI로부터 사용자는 지원되는 모든 앱에서 파일을 선택할 수 있는 것입니다.

    -

    {@link android.content.Intent#ACTION_OPEN_DOCUMENT}는 -{@link android.content.Intent#ACTION_GET_CONTENT}를 +

    {@link android.content.Intent#ACTION_OPEN_DOCUMENT}는 +{@link android.content.Intent#ACTION_GET_CONTENT}를 대체할 목적으로 만들어진 것이 아닙니다. 어느 것을 사용해야 할지는 각자의 앱에 필요한 것이 무엇인지에 좌우됩니다.

    -

    이 섹션에서는 -{@link android.content.Intent#ACTION_OPEN_DOCUMENT} 및 +

    이 섹션에서는 +{@link android.content.Intent#ACTION_OPEN_DOCUMENT} 및 {@link android.content.Intent#ACTION_CREATE_DOCUMENT} 인텐트를 근거로 클라이언트 앱을 작성하는 방법을 설명합니다.

    -다음 조각에서는 {@link android.content.Intent#ACTION_OPEN_DOCUMENT}를 -사용하여 이미지 파일이 들어 있는 문서 제공자를 +다음 조각에서는 {@link android.content.Intent#ACTION_OPEN_DOCUMENT}를 +사용하여 이미지 파일이 들어 있는 문서 제공자를 검색합니다.

    private static final int READ_REQUEST_CODE = 42;
    @@ -277,7 +277,7 @@ public void performFileSearch() {
     
  • 앱이 {@link android.content.Intent#ACTION_OPEN_DOCUMENT} 인텐트를 실행시키면 이는 일치하는 문서 제공자를 모두 표시하는 선택기를 시작합니다.
  • -
  • {@link android.content.Intent#CATEGORY_OPENABLE} 카테고리를 +
  • {@link android.content.Intent#CATEGORY_OPENABLE} 카테고리를 인텐트에 추가하면 결과를 필터링하여 이미지 파일 등 열 수 있는 문서만 표시합니다.
  • {@code intent.setType("image/*")} 문으로 한층 더 필터링을 수행하여 @@ -286,10 +286,10 @@ MIME 데이터 유형이 이미지인 문서만 표시하도록 합니다.
  • 결과 처리

    -

    사용자가 선택기에서 문서를 선택하면 -{@link android.app.Activity#onActivityResult onActivityResult()}가 호출됩니다. +

    사용자가 선택기에서 문서를 선택하면 +{@link android.app.Activity#onActivityResult onActivityResult()}가 호출됩니다. 선택한 문서를 가리키는 URI는 {@code resultData} -매개변수 안에 들어있습니다. 이 URI를 {@link android.content.Intent#getData getData()}를 사용하여 추출합니다. +매개변수 안에 들어있습니다. 이 URI를 {@link android.content.Intent#getData getData()}를 사용하여 추출합니다. 일단 이것을 가지게 되면 이를 사용하여 사용자가 원하는 문서를 검색하면 됩니다. 예:

    @@ -318,7 +318,7 @@ public void onActivityResult(int requestCode, int resultCode,

    문서 메타데이터 살펴보기

    -

    문서의 URI를 얻은 다음에는 그 문서의 메타데이터에 액세스할 수 있습니다. 이 +

    문서의 URI를 얻은 다음에는 그 문서의 메타데이터에 액세스할 수 있습니다. 이 조각은 해당 URI가 나타내는 문서의 메타데이터를 가져와 다음과 같이 기록합니다.

    public void dumpImageMetaData(Uri uri) {
    @@ -365,7 +365,7 @@ public void onActivityResult(int requestCode, int resultCode,
     
     

    문서 열기

    -

    문서의 URI를 얻은 다음에는 문서를 열 수도 있고 원하는 대로 무엇이든 +

    문서의 URI를 얻은 다음에는 문서를 열 수도 있고 원하는 대로 무엇이든 할 수 있습니다.

    비트맵

    @@ -382,14 +382,14 @@ public void onActivityResult(int requestCode, int resultCode, }
    -

    이 작업을 UI 스레드에서 해서는 안 된다는 점을 유의하십시오. 이것은 배경에서 하되, -{@link android.os.AsyncTask}를 사용합니다. 비트맵을 열고 나면 이를 +

    이 작업을 UI 스레드에서 해서는 안 된다는 점을 유의하십시오. 이것은 배경에서 하되, +{@link android.os.AsyncTask}를 사용합니다. 비트맵을 열고 나면 이를 {@link android.widget.ImageView}로 표시할 수 있습니다.

    InputStream 가져오기

    -

    다음은 URI에서 {@link java.io.InputStream}을 가져오는 방법을 예시로 나타낸 것입니다. 이 조각에서 +

    다음은 URI에서 {@link java.io.InputStream}을 가져오는 방법을 예시로 나타낸 것입니다. 이 조각에서 파일의 줄이 문자열로 읽히고 있습니다.

    private String readTextFromUri(Uri uri) throws IOException {
    @@ -409,9 +409,9 @@ public void onActivityResult(int requestCode, int resultCode,
     
     

    새 문서 생성하기

    -

    개발자의 앱은 문서 제공자에서 새 문서를 생성할 수 있습니다. 이때 +

    개발자의 앱은 문서 제공자에서 새 문서를 생성할 수 있습니다. 이때 {@link android.content.Intent#ACTION_CREATE_DOCUMENT} - 인텐트를 사용하면 됩니다. 파일을 생성하려면 인텐트에 MIME 유형과 파일 이름을 부여하고, + 인텐트를 사용하면 됩니다. 파일을 생성하려면 인텐트에 MIME 유형과 파일 이름을 부여하고, 고유한 요청 코드로 이를 시작하면 됩니다. 나머지는 여러분 대신 알아서 해드립니다.

    @@ -440,15 +440,15 @@ private void createFile(String mimeType, String fileName) { }
    -

    새 문서를 생성하고 나면 -{@link android.app.Activity#onActivityResult onActivityResult()}에서 URI를 가져와 거기에 계속해서 +

    새 문서를 생성하고 나면 +{@link android.app.Activity#onActivityResult onActivityResult()}에서 URI를 가져와 거기에 계속해서 쓸 수 있습니다.

    문서 삭제하기

    -

    어느 문서에 대한 URI가 있고 해당 문서의 +

    어느 문서에 대한 URI가 있고 해당 문서의 {@link android.provider.DocumentsContract.Document#COLUMN_FLAGS Document.COLUMN_FLAGS} -에 +에 {@link android.provider.DocumentsContract.Document#FLAG_SUPPORTS_DELETE SUPPORTS_DELETE}가 들어 있는 경우, 해당 문서를 삭제할 수 있습니다. 예:

    @@ -459,9 +459,9 @@ DocumentsContract.deleteDocument(getContentResolver(), uri);

    문서 편집하기

    준비된 텍스트 문서를 편집하는 데 SAF를 사용할 수 있습니다. -이 조각은 -{@link android.content.Intent#ACTION_OPEN_DOCUMENT} 인텐트를 실행하며 -{@link android.content.Intent#CATEGORY_OPENABLE} 카테고리를 사용해 +이 조각은 +{@link android.content.Intent#ACTION_OPEN_DOCUMENT} 인텐트를 실행하며 +{@link android.content.Intent#CATEGORY_OPENABLE} 카테고리를 사용해 열 수 있는 문서만 표시하도록 합니다. 이것을 한층 더 필터링하여 텍스트 파일만 표시하게 하려면 다음과 같이 합니다.

    @@ -486,10 +486,10 @@ private static final int EDIT_REQUEST_CODE = 44;
     

    다음으로, {@link android.app.Activity#onActivityResult onActivityResult()} -(결과 처리 참조)에서 코드를 호출하여 편집 작업을 수행하도록 하면 됩니다. +(결과 처리 참조)에서 코드를 호출하여 편집 작업을 수행하도록 하면 됩니다. 다음 조각은 {@link android.content.ContentResolver}에서 {@link java.io.FileOutputStream} -을 가져온 것입니다. 이것은 기본적으로 "쓰기" 모드를 사용합니다. -필요한 최소 수량의 액세스만을 요청하는 것이 가장 좋으니 쓰기만 필요하다면 +을 가져온 것입니다. 이것은 기본적으로 "쓰기" 모드를 사용합니다. +필요한 최소 수량의 액세스만을 요청하는 것이 가장 좋으니 쓰기만 필요하다면 읽기/쓰기를 요청하지 마십시오.

    private void alterDocument(Uri uri) {
    @@ -512,16 +512,16 @@ private static final int EDIT_REQUEST_CODE = 44;
     
     

    권한 유지

    -

    앱이 읽기 또는 쓰기 작업에 대한 파일을 열면 시스템이 앱에 해당 파일에 대한 URI 권한 허가를 +

    앱이 읽기 또는 쓰기 작업에 대한 파일을 열면 시스템이 앱에 해당 파일에 대한 URI 권한 허가를 부여합니다. 이것은 사용자의 장치를 다시 시작할 때까지 유지됩니다. -하지만 만일 앱이 이미지 편집 앱이고, 사용자가 여러분의 앱에서 바로 편집한 5개의 이미지에 -액세스할 수 있도록 하고자 한다고 가정해봅시다. 사용자의 기기가 재시작되면 -여러분이 사용자에게 시스템 선택기를 다시 보내 해당 파일을 검색하도록 해야 할 텐데, +하지만 만일 앱이 이미지 편집 앱이고, 사용자가 여러분의 앱에서 바로 편집한 5개의 이미지에 +액세스할 수 있도록 하고자 한다고 가정해봅시다. 사용자의 기기가 재시작되면 +여러분이 사용자에게 시스템 선택기를 다시 보내 해당 파일을 검색하도록 해야 할 텐데, 이것은 물론 이상적인 것과는 거리가 멉니다.

    이런 일이 일어나지 않도록 방지하기 위해 시스템이 앱에 부여한 권한을 유지할 수 있습니다. -여러분의 앱은 시스템이 제공하는 유지 가능한 URI 권한 허가를 -효율적으로 "받아들입니다". 이렇게 하면 사용자가 여러분의 앱을 통해 파일에 지속적인 액세스 권한을 가질 수 있으며, +여러분의 앱은 시스템이 제공하는 유지 가능한 URI 권한 허가를 +효율적으로 "받아들입니다". 이렇게 하면 사용자가 여러분의 앱을 통해 파일에 지속적인 액세스 권한을 가질 수 있으며, 이는 기기가 다시 시작되더라도 관계 없습니다.

    @@ -531,65 +531,65 @@ private static final int EDIT_REQUEST_CODE = 44; // Check for the freshest data. getContentResolver().takePersistableUriPermission(uri, takeFlags);
    -

    마지막 한 단계가 남았습니다. 여러분의 앱이 액세스한 가장 최근의 URI를 -저장해두었을 수 있지만, 이는 더 이상 유효하지 않을 수 있습니다. 또 다른 앱이 문서를 -삭제하거나 수정했을 수 있기 때문입니다. 따라서, 항상 -{@code getContentResolver().takePersistableUriPermission()}을 +

    마지막 한 단계가 남았습니다. 여러분의 앱이 액세스한 가장 최근의 URI를 +저장해두었을 수 있지만, 이는 더 이상 유효하지 않을 수 있습니다. 또 다른 앱이 문서를 +삭제하거나 수정했을 수 있기 때문입니다. 따라서, 항상 +{@code getContentResolver().takePersistableUriPermission()}을 호출하여 최신 데이터를 확인해야 합니다.

    사용자 지정 문서 제공자 작성하기

    -파일용 저장소 서비스를 제공하는 앱을 개발 중인 경우(예를 들어 -클라우드 저장 서비스 등), SAF를 통해 파일을 사용할 수 있도록 하려면 사용자 지정 문서 제공자를 +파일용 저장소 서비스를 제공하는 앱을 개발 중인 경우(예를 들어 +클라우드 저장 서비스 등), SAF를 통해 파일을 사용할 수 있도록 하려면 사용자 지정 문서 제공자를 작성하면 됩니다. 이 섹션에서는 이렇게 하는 방법을 설명합니다.

    매니페스트

    -

    사용자 지정 문서 제공자를 구현하려면 애플리케이션의 매니페스트에 다음과 같은 항목을 +

    사용자 지정 문서 제공자를 구현하려면 애플리케이션의 매니페스트에 다음과 같은 항목을 추가하십시오.

    • API 레벨 19 이상의 대상.
    • -
    • 사용자 지정 저장소 제공자를 선언하는 <provider> +
    • 사용자 지정 저장소 제공자를 선언하는 <provider> 요소.
    • -
    • 제공자의 이름은 그 클래스 이름이며 여기에 패키지 이름도 포함됩니다. +
    • 제공자의 이름은 그 클래스 이름이며 여기에 패키지 이름도 포함됩니다. 예: com.example.android.storageprovider.MyCloudProvider
    • -
    • 권한의 이름, 이는 패키지 이름과 같으며(이 예시에서는 +
    • 권한의 이름, 이는 패키지 이름과 같으며(이 예시에서는 com.example.android.storageprovider)여기에 콘텐츠 제공자 유형을 더합니다 (documents). 예: {@code com.example.android.storageprovider.documents}
    • android:exported 속성을 "true"로 설정. 제공자를 내보내 다른 앱이 볼 수 있도록 해야 합니다.
    • -
    • android:grantUriPermissions 속성을 -"true"로 설정. 이렇게 설정하면 시스템이 여러분의 제공자 안에 있는 콘텐츠에 액세스하도록 다른 앱에 -권한을 허가할 수 있게 해줍니다. 특정 문서에 대한 권한 부여를 유지하는 방법에 대한 논의는 +
    • android:grantUriPermissions 속성을 +"true"로 설정. 이렇게 설정하면 시스템이 여러분의 제공자 안에 있는 콘텐츠에 액세스하도록 다른 앱에 +권한을 허가할 수 있게 해줍니다. 특정 문서에 대한 권한 부여를 유지하는 방법에 대한 논의는 권한 유지를 참조하십시오.
    • {@code MANAGE_DOCUMENTS} 권한. 기본적으로 제공자는 누구나 이용할 수 있습니다. - 이 권한을 추가하면 여러분의 제공자를 시스템에 제한하게 됩니다. + 이 권한을 추가하면 여러분의 제공자를 시스템에 제한하게 됩니다. 이 제한은 보안상 매우 중요합니다.
    • -
    • {@code android:enabled} 속성을 리소스 파일에서 정의한 부울 값으로 -설정합니다. 이 속성의 목적은 Android 4.3 이하에서 실행되는 기기에서 제공자를 비활성화하는 데 있습니다. -예를 들어 {@code android:enabled="@bool/atLeastKitKat"} 등입니다. 이 속성을 +
    • {@code android:enabled} 속성을 리소스 파일에서 정의한 부울 값으로 +설정합니다. 이 속성의 목적은 Android 4.3 이하에서 실행되는 기기에서 제공자를 비활성화하는 데 있습니다. +예를 들어 {@code android:enabled="@bool/atLeastKitKat"} 등입니다. 이 속성을 매니페스트에 추가하는 것 이외에도 다음과 같은 작업을 해야 합니다.
        -
      • {@code res/values/} 아래의 {@code bool.xml} 리소스 파일에 +
      • {@code res/values/} 아래의 {@code bool.xml} 리소스 파일에 이 라인을 추가합니다.
        <bool name="atLeastKitKat">false</bool>
      • -
      • {@code res/values-v19/} 아래의 {@code bool.xml} 리소스 파일에 +
      • {@code res/values-v19/} 아래의 {@code bool.xml} 리소스 파일에 이 라인을 추가합니다.
        <bool name="atLeastKitKat">true</bool>
    • -{@code android.content.action.DOCUMENTS_PROVIDER} 동작을 포함한 인텐트 필터가 있어야 +{@code android.content.action.DOCUMENTS_PROVIDER} 동작을 포함한 인텐트 필터가 있어야 시스템이 제공자를 검색할 때 여러분의 제공자가 선택기에 나타날 수 있습니다.
    @@ -619,31 +619,31 @@ getContentResolver().takePersistableUriPermission(uri, takeFlags);

    Android 4.3 이하에서 실행되는 기기 지원

    -{@link android.content.Intent#ACTION_OPEN_DOCUMENT} 인텐트는 -Android 4.4 이상에서 실행되는 기기에서만 사용할 수 있습니다. -애플리케이션이 {@link android.content.Intent#ACTION_GET_CONTENT}를 지원하도록 하여 -Android 4.3 이하에서 실행되는 기기에도 적용되도록 하려면 Android 4.4 이상에서 실행되는 기기용 매니페스트에 있는 +{@link android.content.Intent#ACTION_OPEN_DOCUMENT} 인텐트는 +Android 4.4 이상에서 실행되는 기기에서만 사용할 수 있습니다. +애플리케이션이 {@link android.content.Intent#ACTION_GET_CONTENT}를 지원하도록 하여 +Android 4.3 이하에서 실행되는 기기에도 적용되도록 하려면 Android 4.4 이상에서 실행되는 기기용 매니페스트에 있는 {@link android.content.Intent#ACTION_GET_CONTENT} - 인텐트 필터를 비활성화해야 합니다. -문서 제공자와 {@link android.content.Intent#ACTION_GET_CONTENT}는 상호 배타적인 것으로 -간주해야 합니다. 둘을 모두 동시에 지원하는 경우, 앱이 시스템 선택기 UI에 + 인텐트 필터를 비활성화해야 합니다. +문서 제공자와 {@link android.content.Intent#ACTION_GET_CONTENT}는 상호 배타적인 것으로 +간주해야 합니다. 둘을 모두 동시에 지원하는 경우, 앱이 시스템 선택기 UI에 두 번 나타나 저장된 데이터에 액세스할 두 가지 서로 다른 방법을 제안하게 됩니다. 이렇게 되면 사용자에게 혼동을 주게 되겠죠.

    -

    다음은 Android 버전 4.4 이상에서 실행되는 기기용 -{@link android.content.Intent#ACTION_GET_CONTENT} 인텐트 필터를 +

    다음은 Android 버전 4.4 이상에서 실행되는 기기용 +{@link android.content.Intent#ACTION_GET_CONTENT} 인텐트 필터를 비활성화하는 데 권장되는 방법입니다.

      -
    1. {@code res/values/} 아래의 {@code bool.xml} 리소스 파일에 +
    2. {@code res/values/} 아래의 {@code bool.xml} 리소스 파일에 이 라인을 추가합니다.
      <bool name="atMostJellyBeanMR2">true</bool>
    3. -
    4. {@code res/values-v19/} 아래의 {@code bool.xml} 리소스 파일에 +
    5. {@code res/values-v19/} 아래의 {@code bool.xml} 리소스 파일에 이 라인을 추가합니다.
      <bool name="atMostJellyBeanMR2">false</bool>
    6. -액티비티 -별칭을 추가하여 버전 4.4(API 레벨 19) 이상을 대상으로 한 {@link android.content.Intent#ACTION_GET_CONTENT} +액티비티 +별칭을 추가하여 버전 4.4(API 레벨 19) 이상을 대상으로 한 {@link android.content.Intent#ACTION_GET_CONTENT} 인텐트 필터를 비활성화합니다. 예:
      @@ -666,13 +666,13 @@ Android 4.3 이하에서 실행되는 기기에도 적용되도록 하려면 And
       

    계약

    -

    사용자 지정 제공자를 작성할 때면 일반적으로 수반되는 작업 중 하나가 -계약 클래스를 구현하는 것입니다. 이는 +

    사용자 지정 제공자를 작성할 때면 일반적으로 수반되는 작업 중 하나가 +계약 클래스를 구현하는 것입니다. 이는 -콘텐츠 제공자 개발자 가이드에서 설명한 것과 같습니다. 계약 클래스는 {@code public final} 클래스로, -이 안에 URI에 대한 상수 정의, 열 이름, MIME 유형 및 제공자에 관련된 -다른 메타 데이터가 들어 있습니다. SAF가 -이와 같은 계약 클래스를 대신 제공해주므로 직접 쓰지 않아도 +콘텐츠 제공자 개발자 가이드에서 설명한 것과 같습니다. 계약 클래스는 {@code public final} 클래스로, +이 안에 URI에 대한 상수 정의, 열 이름, MIME 유형 및 제공자에 관련된 +다른 메타 데이터가 들어 있습니다. SAF가 +이와 같은 계약 클래스를 대신 제공해주므로 직접 쓰지 않아도 됩니다.

    -

    예를 들어 다음은 여러분의 문서 제공자가 문서 또는 루트에 대해 쿼리된 경우 +

    예를 들어 다음은 여러분의 문서 제공자가 문서 또는 루트에 대해 쿼리된 경우 커서로 반환할 수 있는 열을 나타낸 것입니다.

    private static final String[] DEFAULT_ROOT_PROJECTION =
    @@ -696,7 +696,7 @@ private static final String[] DEFAULT_DOCUMENT_PROJECTION = new
     
     

    하위 클래스 DocumentsProvider

    -

    사용자 지정 문서 제공자를 작성하기 위한 다음 단계는 +

    사용자 지정 문서 제공자를 작성하기 위한 다음 단계는 추상 클래스 {@link android.provider.DocumentsProvider}를 하위 클래스로 만드는 것입니다. 최소한 다음과 같은 메서드를 구현해야 합니다.

    @@ -710,22 +710,22 @@ private static final String[] DEFAULT_DOCUMENT_PROJECTION = new
  • {@link android.provider.DocumentsProvider#openDocument openDocument()}
  • -

    꼭 구현해야만 하는 메서드는 이들뿐이지만, 개발자 여러분이 구현하고자 하는 메서드는 이보다 -훨씬 많을 수도 있습니다. 자세한 내용은{@link android.provider.DocumentsProvider} +

    꼭 구현해야만 하는 메서드는 이들뿐이지만, 개발자 여러분이 구현하고자 하는 메서드는 이보다 +훨씬 많을 수도 있습니다. 자세한 내용은{@link android.provider.DocumentsProvider} 를 참조하십시오.

    QueryRoots 구현

    {@link android.provider.DocumentsProvider#queryRoots -queryRoots()} 구현은 반드시 {@link android.database.Cursor}를 반환해야 하며, -이는 문서 제공자의 모든 루트 디렉터리를 가리켜야 합니다. 이때 +queryRoots()} 구현은 반드시 {@link android.database.Cursor}를 반환해야 하며, +이는 문서 제공자의 모든 루트 디렉터리를 가리켜야 합니다. 이때 {@link android.provider.DocumentsContract.Root}에서 정의한 열을 사용합니다.

    -

    다음 조각에서 {@code projection} 매개변수는 +

    다음 조각에서 {@code projection} 매개변수는 발신자가 돌려받고자 하는 특정 필드를 나타냅니다. 이 조각은 새 커서를 생성하며 -그에 하나의 행을 추가합니다. 하나의 루트, -다운로드 또는 이미지와 같은 최상위 레벨 디렉터리가 해당됩니다. 대부분의 제공자에는 루트가 하나뿐입니다. 하나 이상이 있을 수도 있습니다. -예를 들어 사용자 계정이 여러 개인 경우가 있습니다. 그런 경우에는 커서에 두 번째 행을 +그에 하나의 행을 추가합니다. 하나의 루트, +다운로드 또는 이미지와 같은 최상위 레벨 디렉터리가 해당됩니다. 대부분의 제공자에는 루트가 하나뿐입니다. 하나 이상이 있을 수도 있습니다. +예를 들어 사용자 계정이 여러 개인 경우가 있습니다. 그런 경우에는 커서에 두 번째 행을 추가하면 됩니다.

    @@ -778,13 +778,13 @@ public Cursor queryRoots(String[] projection) throws FileNotFoundException {
     
     

    {@link android.provider.DocumentsProvider#queryChildDocuments queryChildDocuments()} - 구현은 반드시 {@link android.database.Cursor}를 반환해야 하며, -이는 지정된 디렉터리 내의 모든 파일을 가리켜야 합니다. 이때 + 구현은 반드시 {@link android.database.Cursor}를 반환해야 하며, +이는 지정된 디렉터리 내의 모든 파일을 가리켜야 합니다. 이때 {@link android.provider.DocumentsContract.Document}에서 정의한 열을 사용합니다.

    -

    이 메서드는 선택기 UI에서 애플리케이션 루트를 선택하는 경우 호출됩니다. -이는 해당 루트 아래 디렉터리의 하위 문서를 가져옵니다. 이것은 루트에서뿐만 아니라 파일 계층의 어느 레벨에서나 -호출할 수 있습니다. 이 조각은 요청한 열로 새 커서를 만든 다음, +

    이 메서드는 선택기 UI에서 애플리케이션 루트를 선택하는 경우 호출됩니다. +이는 해당 루트 아래 디렉터리의 하위 문서를 가져옵니다. 이것은 루트에서뿐만 아니라 파일 계층의 어느 레벨에서나 +호출할 수 있습니다. 이 조각은 요청한 열로 새 커서를 만든 다음, 상위 디렉터리에 있는 모든 직속 하위에 대한 정보를 커서에 추가합니다. 하위는 이미지, 또 다른 디렉터리가 될 수도 있고 어느 파일이라도 될 수 있습니다.

    @@ -808,13 +808,13 @@ public Cursor queryChildDocuments(String parentDocumentId, String[] projection,

    {@link android.provider.DocumentsProvider#queryDocument queryDocument()} - 구현은 반드시 {@link android.database.Cursor}를 반환해야 하며, + 구현은 반드시 {@link android.database.Cursor}를 반환해야 하며, 이는 지정된 파일을 가리켜야 합니다. 이때 {@link android.provider.DocumentsContract.Document}에서 정의한 열을 사용합니다.

    {@link android.provider.DocumentsProvider#queryDocument queryDocument()} - 메서드는 -{@link android.provider.DocumentsProvider#queryChildDocuments queryChildDocuments()}에서 + 메서드는 +{@link android.provider.DocumentsProvider#queryChildDocuments queryChildDocuments()}에서 전달된 것과 같은 정보를 반환하지만, 특정한 파일에만 해당됩니다.

    @@ -832,12 +832,12 @@ public Cursor queryDocument(String documentId, String[] projection) throws

    OpenDocument 구현

    -

    지정된 파일을 나타내는 +

    지정된 파일을 나타내는 {@link android.os.ParcelFileDescriptor}를 반환하려면 {@link android.provider.DocumentsProvider#openDocument openDocument()}를 구현해야 합니다. 다른 앱들이 반환된 {@link android.os.ParcelFileDescriptor}를 - 사용하여 데이터를 스트리밍할 수 있습니다. 시스템은 사용자가 파일을 선택하고 -클라이언트 앱이 이에 대한 액세스를 요청하면서 -{@link android.content.ContentResolver#openFileDescriptor openFileDescriptor()}를 사용할 때 이 메서드를 호출합니다. + 사용하여 데이터를 스트리밍할 수 있습니다. 시스템은 사용자가 파일을 선택하고 +클라이언트 앱이 이에 대한 액세스를 요청하면서 +{@link android.content.ContentResolver#openFileDescriptor openFileDescriptor()}를 사용할 때 이 메서드를 호출합니다. 예를 들면 다음과 같습니다.

    @Override
    @@ -885,8 +885,8 @@ public ParcelFileDescriptor openDocument(final String documentId,
     

    보안

    여러분의 문서 제공자가 암호로 보호된 클라우드 저장소 서비스이고 -여러분은 사용자가 파일을 공유하기 전에 우선 로그인부터 하도록 확실히 해두고 싶다고 가정합니다. -사용자가 로그인되지 않은 경우 앱은 어떻게 해야 합니까? 해법은 +여러분은 사용자가 파일을 공유하기 전에 우선 로그인부터 하도록 확실히 해두고 싶다고 가정합니다. +사용자가 로그인되지 않은 경우 앱은 어떻게 해야 합니까? 해법은 {@link android.provider.DocumentsProvider#queryRoots queryRoots()} 구현에서 루트를 반환하지 않는 것입니다. 다시 말해, 텅 빈 루트 커서를 반환하는 것입니다.

    @@ -901,11 +901,11 @@ public Cursor queryRoots(String[] projection) throws FileNotFoundException {

    또 다른 단계는 {@code getContentResolver().notifyChange()}를 호출하는 것입니다. -{@link android.provider.DocumentsContract}를 기억하십니까? 이것을 사용하는 이유는 -바로 이 URI를 만들기 위해서입니다. 다음 조각은 사용자의 로그인 상태가 변경될 때마다 -시스템이 문서 제공자의 루트를 쿼리하도록 지시하고 있습니다. 사용자가 로그인되어 있지 않은 상태에서 -{@link android.provider.DocumentsProvider#queryRoots queryRoots()}를 호출하면 -위에서 나타낸 것과 같이 빈 커서를 반환합니다. 이렇게 하면 사용자가 제공자에 로그인되었을 때만 +{@link android.provider.DocumentsContract}를 기억하십니까? 이것을 사용하는 이유는 +바로 이 URI를 만들기 위해서입니다. 다음 조각은 사용자의 로그인 상태가 변경될 때마다 +시스템이 문서 제공자의 루트를 쿼리하도록 지시하고 있습니다. 사용자가 로그인되어 있지 않은 상태에서 +{@link android.provider.DocumentsProvider#queryRoots queryRoots()}를 호출하면 +위에서 나타낸 것과 같이 빈 커서를 반환합니다. 이렇게 하면 사용자가 제공자에 로그인되었을 때만 제공자의 문서를 사용할 수 있도록 보장할 수 있습니다.

    private void onLoginButtonClick() {
    diff --git a/docs/html-intl/intl/ko/guide/topics/resources/accessing-resources.jd b/docs/html-intl/intl/ko/guide/topics/resources/accessing-resources.jd
    index be9dd6bb0b20d..f323280f9d78e 100644
    --- a/docs/html-intl/intl/ko/guide/topics/resources/accessing-resources.jd
    +++ b/docs/html-intl/intl/ko/guide/topics/resources/accessing-resources.jd
    @@ -7,7 +7,7 @@ parent.link=index.html
     

    간략히 보기

      -
    • 리소스는 {@code R.java}의 정수를 사용하는 코드, 예를 들어 +
    • 리소스는 {@code R.java}의 정수를 사용하는 코드, 예를 들어 {@code R.drawable.myimage}에서 참조할 수 있습니다.
    • 리소스는 특수 XML 구문을 사용하는 리소스, 예를 들어 {@code @drawable/myimage}에서 참조할 수 있습니다.
    • @@ -42,25 +42,25 @@ parent.link=index.html -

      일단 어떤 리소스를 애플리케이션에 제공한 다음에는(리소스 제공에서 논의), -해당 리소스의 리소스 ID를 참조함으로써 이를 적용할 수 있습니다. 모든 리소스 ID는 +

      일단 어떤 리소스를 애플리케이션에 제공한 다음에는(리소스 제공에서 논의), +해당 리소스의 리소스 ID를 참조함으로써 이를 적용할 수 있습니다. 모든 리소스 ID는 {@code aapt} 도구가 자동으로 생성하는 프로젝트의 {@code R} 클래스에서 정의됩니다.

      애플리케이션이 컴파일링되면, {@code aapt}가 {@code R} 클래스를 생성하며, 이 클래스 안에 {@code -res/} 디렉터리에 있는 모든 리소스의 -리소스 ID가 들어있습니다. 각 리소스 유형에는 {@code R} 하위 클래스가 있고(예: 모든 드로어블 리소스에 대한 +res/} 디렉터리에 있는 모든 리소스의 +리소스 ID가 들어있습니다. 각 리소스 유형에는 {@code R} 하위 클래스가 있고(예: 모든 드로어블 리소스에 대한 {@code R.drawable}), 해당 유형의 각 리소스에는 정적 -정수가 있습니다(예: {@code R.drawable.icon}). 이 정수가 +정수가 있습니다(예: {@code R.drawable.icon}). 이 정수가 리소스를 검색하는 데 사용할 수 있는 리소스 ID입니다.

      -

      {@code R} 클래스가 리소스 ID가 지정되는 곳이기는 하지만, 리소스 ID를 찾기 위해 +

      {@code R} 클래스가 리소스 ID가 지정되는 곳이기는 하지만, 리소스 ID를 찾기 위해 이곳을 볼 필요는 전혀 없습니다. 하나의 리소스 ID는 항상 다음과 같이 구성됩니다.

      • 리소스 유형: 각 리소스는 "유형"으로 그룹화됩니다. 예: {@code string}, {@code drawable} 및 {@code layout} 다양한 유형에 관한 자세한 정보는 리소스 유형을 참조하십시오.
      • -
      • 리소스 이름: -리소스가 단순 값(예: 문자열 등)일 경우, +
      • 리소스 이름: +리소스가 단순 값(예: 문자열 등)일 경우, 확장자를 제외한 파일 이름이나 XML {@code android:name} 속성 값 중 하나입니다.
      @@ -69,14 +69,14 @@ string}, {@code drawable} 및 {@code layout} 다양한 유형에 관한 자세
    • 코드 내부에서: {@code R} 클래스의 하위 클래스에서 정적 정수를 사용합니다. 예:
      R.string.hello
      -

      {@code string}은 리소스 유형이고 {@code hello}는 리소스 이름입니다. 리소스 ID를 이 형식으로 제공하면 리소스에 액세스할 수 있는 -Android API가 많습니다. +

      {@code string}은 리소스 유형이고 {@code hello}는 리소스 이름입니다. 리소스 ID를 이 형식으로 제공하면 리소스에 액세스할 수 있는 +Android API가 많습니다. 코드 내 리소스 액세스를 참조하십시오.

    • -
    • XML 내부에서: {@code R} 클래스에서 정의된 +
    • XML 내부에서: {@code R} 클래스에서 정의된 리소스 ID에 상응하기도 하는 특수 XML 구문을 사용합니다. 예:
      @string/hello
      -

      {@code string}은 리소스 유형이고 {@code hello}는 리소스 이름입니다. 이 +

      {@code string}은 리소스 유형이고 {@code hello}는 리소스 이름입니다. 이 구문은 리소스로 값을 제공할 것으로 예상되는 어느 곳에서나 XML 리소스 형태로 사용할 수 있습니다. XML에서 리소스 액세스를 참조하십시오.

    @@ -94,20 +94,20 @@ imageView.setImageResource(R.drawable.myimage);

    {@link -android.content.res.Resources}에서 메서드를 사용하는 개별 리소스를 검색할 수도 있으며, 이는 +android.content.res.Resources}에서 메서드를 사용하는 개별 리소스를 검색할 수도 있으며, 이는 {@link android.content.Context#getResources()}로 인스턴스를 가져올 수 있습니다.

    -

    이미지나 문자열과 같은 애플리케이션 리소스는 항상 코드에서 외부화해야 합니다. -그래야 이들을 독립적으로 유지관리할 수 있습니다. 특정 기기 구성에 대한 대체 리소스도 -제공해야 합니다. 이것은 특별하게 명명한 리소스 디렉터리에 그룹화하는 방법을 씁니다. Android는 -런타임에 현재 구성을 근거로 적절한 리소스를 사용합니다. 예를 들어 -여러 가지 화면 크기에 따라 여러 가지 UI 레이아웃을 제공하거나 언어 설정에 따라 +

    이미지나 문자열과 같은 애플리케이션 리소스는 항상 코드에서 외부화해야 합니다. +그래야 이들을 독립적으로 유지관리할 수 있습니다. 특정 기기 구성에 대한 대체 리소스도 +제공해야 합니다. 이것은 특별하게 명명한 리소스 디렉터리에 그룹화하는 방법을 씁니다. Android는 +런타임에 현재 구성을 근거로 적절한 리소스를 사용합니다. 예를 들어 +여러 가지 화면 크기에 따라 여러 가지 UI 레이아웃을 제공하거나 언어 설정에 따라 각기 다른 문자열을 제공하고자 할 수 있습니다.

    애플리케이션 리소스를 외부화하면 프로젝트 {@code R} 클래스에서 발생하는 리소스 ID로 액세스할 수 있습니다. 애플리케이션에서 리소스를 사용하는 방법은 리소스 -액세스에서 설명합니다. 이 문서에서는 Android 프로젝트에서 리소스를 그룹화하는 방법과 특정 기기 구성에 대한 +액세스에서 설명합니다. 이 문서에서는 Android 프로젝트에서 리소스를 그룹화하는 방법과 특정 기기 구성에 대한 대체 리소스를 제공하는 법을 보여드립니다.

    @@ -75,10 +75,10 @@ MyProject/ ) 포함하는 것을 볼 수 있습니다. 리소스 디렉터리 이름은 중요하며 표1에 설명되어 있습니다.

    -

    참고: Mipmap 폴더를 사용하는 자세한 방법은 +

    참고: Mipmap 폴더를 사용하는 자세한 방법은 프로젝트 관리 개요를 참조하십시오.

    -

    표 1. 프로젝트 +

    표 1. 프로젝트 {@code res/} 디렉터리 내부에서 지원하는 리소스 디렉터리입니다.

    @@ -89,13 +89,13 @@ MyProject/ - - @@ -126,8 +126,8 @@ MyProject/ - @@ -139,32 +139,32 @@ MyProject/ - - @@ -184,21 +184,21 @@ assets/} 디렉터리에 몇몇 리소스를 저장해두는 것을 고려해
    animator/속성 + 속성 애니메이션을 정의하는 XML 파일입니다.
    anim/tween + tween 애니메이션을 정의하는 XML 파일입니다 (속성 애니메이션도 이 디렉터리에 저장할 수 있지만 두 가지 유형을 구분하기 위해 속성 애니메이션에는 {@code animator/} 디렉터리가 기본 설정됩니다 ).
    mipmap/각기 다른 시작 관리자 아이콘 밀도에 대한 드로어블 파일입니다. -{@code mipmap/} 폴더로 시작 관리자 아이콘을 관리하는 자세한 방법은 + 각기 다른 시작 관리자 아이콘 밀도에 대한 드로어블 파일입니다. +{@code mipmap/} 폴더로 시작 관리자 아이콘을 관리하는 자세한 방법은 프로젝트 관리 개요를 참조하십시오.
    menu/옵션 메뉴, 컨텍스트 메뉴 또는 하위 + 옵션 메뉴, 컨텍스트 메뉴 또는 하위 메뉴 등과 같은 애플리케이션 메뉴를 정의하는 XML입니다. 메뉴 리소스를 참조하십시오.
    raw/

    원시 형태로 저장하기 위한 임의의 파일입니다. 원시 +

    원시 형태로 저장하기 위한 임의의 파일입니다. 원시 {@link java.io.InputStream}으로 이런 리소스를 열려면 리소스 ID, {@code R.raw.filename}으로 {@link android.content.res.Resources#openRawResource(int) Resources.openRawResource()}를 호출합니다.

    -

    그러나 원본 파일 이름과 파일 계층에 액세스해야 하는 경우, +

    그러나 원본 파일 이름과 파일 계층에 액세스해야 하는 경우, ({@code res/raw/}가 아니라) {@code -assets/} 디렉터리에 몇몇 리소스를 저장해두는 것을 고려해 볼 수 있습니다. {@code assets/}에 있는 파일에는 +assets/} 디렉터리에 몇몇 리소스를 저장해두는 것을 고려해 볼 수 있습니다. {@code assets/}에 있는 파일에는 리소스 ID가 주어지지 않으므로, 이들을 읽는 유일한 방법은 {@link android.content.res.AssetManager}를 사용하는 것뿐입니다.

    values/

    문자열, 정수 및 색과 같은 단순 값이 들어있는 XML 파일입니다.

    -

    다른 {@code res/} 하위 디렉터리에 있는 XML 리소스 파일은 XML 파일 이름을 근거로 +

    다른 {@code res/} 하위 디렉터리에 있는 XML 리소스 파일은 XML 파일 이름을 근거로 하나의 리소스를 정의하는 반면, {@code values/} 디렉터리에 있는 파일은 여러 개의 리소스를 설명합니다. -이 디렉터리 안에 있는 파일의 경우, {@code <resources>} 요소의 각 하위 요소가 리소스를 하나씩 -정의합니다. 예를 들어 {@code <string>} 요소는 +이 디렉터리 안에 있는 파일의 경우, {@code <resources>} 요소의 각 하위 요소가 리소스를 하나씩 +정의합니다. 예를 들어 {@code <string>} 요소는 {@code R.string} 리소스를 생성하고 {@code <color>} 요소는 {@code R.color} 리소스를 생성합니다.

    각 리소스가 자체 XML 요소로 정의되므로, 원하는 대로 파일을 정의하고 하나의 파일에 여러 가지 리소스 유형을 -배정할 수 있습니다. 하지만 명확히 하려면 여러 가지 파일에 +배정할 수 있습니다. 하지만 명확히 하려면 여러 가지 파일에 각기 고유한 리소스를 배치하는 것이 좋을 수도 있습니다. 예를 들어, 다음은 이 디렉터리에서 생성할 수 있는 리소스를 위한 파일 이름 명명법입니다.

      @@ -176,7 +176,7 @@ assets/} 디렉터리에 몇몇 리소스를 저장해두는 것을 고려해
    • 스타일을 위한 styles.xml

    문자열 리소스, -스타일 리소스 및 +스타일 리소스자세한 리소스 유형을 참조하십시오.

    xml/ 런타임에 읽을 수 있는 임의의 XML 파일로, 이때 {@link -android.content.res.Resources#getXml(int) Resources.getXML()}을 호출하는 방법을 씁니다. 다양한 XML 구성 파일을 여기에 저장해야 합니다. 예를 들어 +android.content.res.Resources#getXml(int) Resources.getXML()}을 호출하는 방법을 씁니다. 다양한 XML 구성 파일을 여기에 저장해야 합니다. 예를 들어 검색 가능한 구성 등이 이에 해당됩니다.
    -

    주의: 리소스 파일을 +

    주의: 리소스 파일을 {@code res/} 디렉터리에 직접 저장하면 절대로 안 됩니다. 컴파일러 오류를 초래하게 됩니다.

    특정 유형의 리소스에 관한 자세한 정보는 리소스 유형 문서를 참조하십시오.

    표1에 정의된 하위 디렉터리에 저장하는 리소스는 "기본" -리소스입니다. 다시 말해, 이러한 리소스가 애플리케이션의 기본 디자인과 콘텐츠를 정의한다는 뜻입니다. +리소스입니다. 다시 말해, 이러한 리소스가 애플리케이션의 기본 디자인과 콘텐츠를 정의한다는 뜻입니다. 그러나, 여러 가지 유형의 Android 구동 기기는 각기 다른 유형의 리소스를 호출할 수도 있습니다. -예를 들어 어느 기기의 화면이 보통보다 큰 편이라면, 추가적인 화면 공간의 이점을 활용할 수 있는 +예를 들어 어느 기기의 화면이 보통보다 큰 편이라면, 추가적인 화면 공간의 이점을 활용할 수 있는 다른 레이아웃 리소스를 제공해야 합니다. 또는, 기기에 다른 언어 설정이 있을 경우 해당 텍스트를 사용자 인터페이스에 번역하는 다른 문자열 리소스를 제공해야 합니다. 여러 가지 기기 구성에 여러 가지 리소스를 제공하려면, @@ -215,10 +215,10 @@ android.content.res.Resources#getXml(int) Resources.getXML()}을 호출하는 그림 1. 서로 다른 두 개의 기기로, 서로 다른 레이아웃 리소스를 사용합니다.

    -

    거의 모든 애플리케이션이 특정 기기 구성을 지원하는 -대체 리소스를 제공해야 합니다. 예를 들어 여러 가지 화면 밀도에 맞는 대체 드로어블 리소스를 -포함시켜야 하며 여러 가지 언어에 맞게 대체 문자열 리소스도 포함시켜야 합니다. Android는 런타임에 -현재 기기 구성을 감지하고 애플리케이션에 대해 적절한 리소스를 +

    거의 모든 애플리케이션이 특정 기기 구성을 지원하는 +대체 리소스를 제공해야 합니다. 예를 들어 여러 가지 화면 밀도에 맞는 대체 드로어블 리소스를 +포함시켜야 하며 여러 가지 언어에 맞게 대체 문자열 리소스도 포함시켜야 합니다. Android는 런타임에 +현재 기기 구성을 감지하고 애플리케이션에 대해 적절한 리소스를 로드합니다.

    리소스 세트에 대하여 구성별로 적절한 대체를 지정하려면 다음과 같이 합니다.

    @@ -231,13 +231,13 @@ android.content.res.Resources#getXml(int) Resources.getXML()}을 호출하는
  • {@code <qualifier>}는 리소스를 사용할 개별 구성을 지정하는 이름입니다(표2에 정의).
  • -

    하나 이상의 {@code <qualifier>}를 추가할 수 있습니다. 각기 대시로 +

    하나 이상의 {@code <qualifier>}를 추가할 수 있습니다. 각기 대시로 구분합니다.

    주의: 여러 한정자를 추가할 때는 -표2에 나열된 것과 같은 순서로 배치해야 합니다. 한정자의 순서가 잘못 지정되면 +표2에 나열된 것과 같은 순서로 배치해야 합니다. 한정자의 순서가 잘못 지정되면 해당 리소스가 무시됩니다.

    -
  • 해당되는 각 대체 리소스를 이 새 디렉터리에 저장하십시오. 이 리소스 파일은 기본 리소스 파일과 +
  • 해당되는 각 대체 리소스를 이 새 디렉터리에 저장하십시오. 이 리소스 파일은 기본 리소스 파일과 똑같은 이름을 지정해야 합니다.
  • @@ -254,21 +254,21 @@ res/

    {@code hdpi} 한정자는 해당 디렉터리의 리소스가 -고화질 화면 기기용이라는 것을 나타냅니다. 각 드로어블 디렉터리의 이미지는 특정 화면 화질에 맞추어 +고화질 화면 기기용이라는 것을 나타냅니다. 각 드로어블 디렉터리의 이미지는 특정 화면 화질에 맞추어 크기가 지정되었으나 파일 이름은 똑같습니다. 이렇게 하면 {@code icon.png} 또는 {@code -background.png} 이미지를 참조하는 데 사용하는 리소스 ID는 항상 같지만 Android가 각 리소스 중에서 현재 기기에 가장 잘 일치하는 -버전을 선택하게 됩니다. 이때 리소스 디렉터리 이름의 한정자를 기기 구성 정보와 +background.png} 이미지를 참조하는 데 사용하는 리소스 ID는 항상 같지만 Android가 각 리소스 중에서 현재 기기에 가장 잘 일치하는 +버전을 선택하게 됩니다. 이때 리소스 디렉터리 이름의 한정자를 기기 구성 정보와 비교하는 방법을 씁니다.

    -

    Android는 여러 가지 구성 한정자를 지원하며 한 디렉터리 이름에 -여러 개의 한정자를 추가할 수 있습니다. 각 한정자를 대시로 구분하면 됩니다. 표 2는 -유효한 구성 한정자를 우선 순위대로 나열한 것입니다. 리소스 디렉터리에 여러 개의 -한정자를 사용하는 경우, 해당 한정자를 디렉터리 이름에 추가할 때 이 표에 나열된 것과 같은 +

    Android는 여러 가지 구성 한정자를 지원하며 한 디렉터리 이름에 +여러 개의 한정자를 추가할 수 있습니다. 각 한정자를 대시로 구분하면 됩니다. 표 2는 +유효한 구성 한정자를 우선 순위대로 나열한 것입니다. 리소스 디렉터리에 여러 개의 +한정자를 사용하는 경우, 해당 한정자를 디렉터리 이름에 추가할 때 이 표에 나열된 것과 같은 순서로 추가해야 합니다.

    -

    표 2. 구성 한정자 +

    표 2. 구성 한정자 이름입니다.

    @@ -285,7 +285,7 @@ background.png} 이미지를 참조하는 데 사용하는 리소스 ID는 항 등. @@ -312,19 +312,19 @@ android.content.res.Configuration#mnc}를 참조하십시오. 이 구성 필드 등. @@ -368,22 +368,22 @@ supportsRtl}을 {@code "true"}로 설정하고 화면의 기본 크기로, 사용 가능한 화면 영역의 가장 짧은 치수가 +나타냅니다. 구체적으로 기기의 smallestWidth는 해당 화면의 이용 가능한 높이와 너비의 +가장 짧은 치수를 말합니다(이것을 화면에 대한 "가능한 한 가장 좁은 너비"로 생각해도 됩니다). 이 한정자를 사용하면 +화면의 현재 방향에 관계 없이 애플리케이션이 해당 UI에서 이용 가능한 너비 중 최소 {@code <N>}dps를 확보하도록 할 수 있습니다.

    -

    예를 들어, 레이아웃에 언제나 +

    예를 들어, 레이아웃에 언제나 600dp 이상의 화면 최소 치수가 필요하다면, 이 한정자를 사용하여 레이아웃 리소스, {@code -res/layout-sw600dp/}를 만들 수 있습니다. 시스템이 이러한 리소스를 사용하는 것은 사용 가능한 화면의 최소 치수가 적어도 600dp가 -되는 경우뿐이며, 이때 600dp라는 크기가 사용자 쪽에서 보기에 높이이든 너비이든 +res/layout-sw600dp/}를 만들 수 있습니다. 시스템이 이러한 리소스를 사용하는 것은 사용 가능한 화면의 최소 치수가 적어도 600dp가 +되는 경우뿐이며, 이때 600dp라는 크기가 사용자 쪽에서 보기에 높이이든 너비이든 관계 없습니다. 이 smallestWidth는 기기의 고정된 화면 크기 특성입니다. 기기의 smallestWidth는 화면 방향이 변경되어도 바뀌지 않습니다.

    기기의 smallestWidth는 화면 장식과 시스템 UI를 감안합니다. 예를 들어, 화면 상에서 최소 너비의 축 주변 공간을 차지하는 영구 UI 요소가 있다면, -시스템은 smallestWidth를 실제 화면 크기보다 작게 선언합니다. -이것은 개발자의 UI가 사용할 수 없는 화면 픽셀이기 때문입니다. 따라서 개발자가 사용하는 값은 -레이아웃에서 요구하는 실제 최소 치수여야 합니다(일반적으로 이 값은 화면의 현재 방향과 관계없이 +시스템은 smallestWidth를 실제 화면 크기보다 작게 선언합니다. +이것은 개발자의 UI가 사용할 수 없는 화면 픽셀이기 때문입니다. 따라서 개발자가 사용하는 값은 +레이아웃에서 요구하는 실제 최소 치수여야 합니다(일반적으로 이 값은 화면의 현재 방향과 관계없이 레이아웃이 지원하는 "최소 너비"가 됩니다.).

    다음의 몇몇 값은 보편적인 화면 크기에 대하여 사용할 수 있습니다.

      @@ -398,16 +398,16 @@ res/layout-sw600dp/}를 만들 수 있습니다. 시스템이 이러한 리소
    • 600x1024mdpi (7인치 태블릿) 등의 화면에는 600을 사용합니다.
    • 720x1280mdpi (10인치 태블릿) 등의 화면에는 720을 사용합니다.
    -

    애플리케이션이 -smallestWidth 한정자의 여러 값이 포함된 여러 리소스 디렉터리를 제공하면, 시스템은 +

    애플리케이션이 +smallestWidth 한정자의 여러 값이 포함된 여러 리소스 디렉터리를 제공하면, 시스템은 기기의 smallestWidth에 가장 가까운(그러나 이를 초과하지 않는) 값을 사용합니다.

    API 레벨 13에서 추가되었습니다.

    이외에도 애플리케이션과 호환되는 최소한의 smallestWidth를 선언하는 {@code -android:requiresSmallestWidthDp} 속성과 +android:requiresSmallestWidthDp} 속성과 기기의 smallestWidth 값을 보유한 {@link -android.content.res.Configuration#smallestScreenWidthDp} +android.content.res.Configuration#smallestScreenWidthDp} 구성 필드도 참조하십시오.

    -

    여러 가지 화면에 맞는 디자인과 한정자 사용에 관한 자세한 정보는 +

    여러 가지 화면에 맞는 디자인과 한정자 사용에 관한 자세한 정보는 다중 화면 지원 개발자 가이드를 참조하십시오.

    @@ -421,21 +421,21 @@ android.content.res.Configuration#smallestScreenWidthDp} 등. @@ -449,25 +449,25 @@ android.content.res.Configuration#smallestScreenWidthDp} 등. @@ -482,39 +482,39 @@ android.content.res.Configuration#smallestScreenWidthDp} @@ -530,9 +530,9 @@ xlarge} 한정자가 태그되어 있지만 기기는 일반 크기 화면일
  • {@code notlong}: QVGA, HVGA 및 VGA 등의 길지 않은 화면
  • API 레벨 4에서 추가되었습니다.

    -

    이것은 순전히 화면 비율에만 기초합니다("긴" 화면이 더 넓습니다). 이는 +

    이것은 순전히 화면 비율에만 기초합니다("긴" 화면이 더 넓습니다). 이는 화면 방향과 관계가 없습니다.

    -

    {@link android.content.res.Configuration#screenLayout}도 참조하십시오. +

    {@link android.content.res.Configuration#screenLayout}도 참조하십시오. 이것은 화면이 긴 화면인지 여부를 나타냅니다.

    @@ -549,10 +549,10 @@ xlarge} 한정자가 태그되어 있지만 기기는 일반 크기 화면일
  • {@code land}: 기기가 가로 방향(수평)입니다.
  • -

    이것은 사용자가 화면을 돌리는 경우 애플리케이션 수명 중에 -변경될 수 있습니다. 이것이 런타임에 애플리케이션에 어떤 영향을 미치는지 알아보려면 +

    이것은 사용자가 화면을 돌리는 경우 애플리케이션 수명 중에 +변경될 수 있습니다. 이것이 런타임에 애플리케이션에 어떤 영향을 미치는지 알아보려면 런타임 변경 처리를 참조하십시오.

    -

    {@link android.content.res.Configuration#orientation} 구성 필드도 참조하십시오. +

    {@link android.content.res.Configuration#orientation} 구성 필드도 참조하십시오. 이는 현재 기기 방향을 나타냅니다.

    @@ -569,21 +569,21 @@ xlarge} 한정자가 태그되어 있지만 기기는 일반 크기 화면일
    • {@code car}: 기기가 차량용 도크에서 표시되고 있습니다.
    • {@code desk}: 기기가 데스크용 도크에서 표시되고 있습니다.
    • -
    • {@code television}: 기기가 텔레비전에서 표시되고 있으며, -UI가 큰 화면에 있고 사용자가 여기에서 멀리 떨어져 있는 -"텐 풋(ten foot)" 환경을 제공하고 있습니다. 이는 주로 DPAD 또는 +
    • {@code television}: 기기가 텔레비전에서 표시되고 있으며, +UI가 큰 화면에 있고 사용자가 여기에서 멀리 떨어져 있는 +"텐 풋(ten foot)" 환경을 제공하고 있습니다. 이는 주로 DPAD 또는 기타 비-포인터 상호 작용 주변을 가리킵니다.
    • -
    • {@code appliance}: 기기가 가전 제품 역할을 하고 있으며, 디스플레이 +
    • {@code appliance}: 기기가 가전 제품 역할을 하고 있으며, 디스플레이 화면이 없습니다.
    • {@code watch}: 기기에 디스플레이 화면이 있고 손목에 착용됩니다.

    API 레벨 8에서 추가되었고, 텔레비전은 API 13에서, 시계는 API 20에서 추가되었습니다.

    -

    기기가 도크에 삽입되거나 제거될 때 앱이 응답하는 방식에 관한 정보는 -도킹 상태 및 유형 +

    기기가 도크에 삽입되거나 제거될 때 앱이 응답하는 방식에 관한 정보는 +도킹 상태 및 유형 판별과 모니터링을 읽어보십시오.

    -

    이것은 사용자가 기기를 도크에 놓는 경우 애플리케이션 수명 중에 +

    이것은 사용자가 기기를 도크에 놓는 경우 애플리케이션 수명 중에 변경될 수 있습니다. 이러한 모드 중 몇 가지는 {@link -android.app.UiModeManager}를 사용하여 활성화 또는 비활성화할 수 있습니다. 이것이 런타임에 애플리케이션에 어떤 영향을 미치는지 알아보려면 런타임 변경 처리를 +android.app.UiModeManager}를 사용하여 활성화 또는 비활성화할 수 있습니다. 이것이 런타임에 애플리케이션에 어떤 영향을 미치는지 알아보려면 런타임 변경 처리를 참조하십시오.

    @@ -599,9 +599,9 @@ android.app.UiModeManager}를 사용하여 활성화 또는 비활성화할 수
  • {@code notnight}: 주간
  • API 레벨 8에서 추가되었습니다.

    -

    이것은 야간 모드가 자동 모드인 상태(기본)에서 애플리케이션의 수명 중에 -변경될 수 있습니다. 이 경우 모드는 하루 중 시간대를 기반으로 변경됩니다. 이 모드는 -{@link android.app.UiModeManager}를 사용하여 활성화 또는 비활성화할 수 있습니다. 이것이 런타임 중 애플리케이션에 어떤 영향을 미치는지 알아보려면 런타임 변경 처리를 +

    이것은 야간 모드가 자동 모드인 상태(기본)에서 애플리케이션의 수명 중에 +변경될 수 있습니다. 이 경우 모드는 하루 중 시간대를 기반으로 변경됩니다. 이 모드는 +{@link android.app.UiModeManager}를 사용하여 활성화 또는 비활성화할 수 있습니다. 이것이 런타임 중 애플리케이션에 어떤 영향을 미치는지 알아보려면 런타임 변경 처리를 참조하십시오.

    @@ -623,33 +623,33 @@ android.app.UiModeManager}를 사용하여 활성화 또는 비활성화할 수
  • {@code mdpi}: 중밀도(일반적인 HVGA에서) 화면, 약 160dpi.
  • {@code hdpi}: 고밀도 화면, 약 240dpi.
  • -
  • {@code xhdpi}: 초고밀도 화면, 약 320dpi. API 레벨 8에서 +
  • {@code xhdpi}: 초고밀도 화면, 약 320dpi. API 레벨 8에서 추가되었습니다.
  • -
  • {@code xxhdpi}: 슈퍼 초고밀도 화면, 약 480dpi. API 레벨 16에서 +
  • {@code xxhdpi}: 슈퍼 초고밀도 화면, 약 480dpi. API 레벨 16에서 추가되었습니다.
  • -
  • {@code xxxhdpi}: 울트라 슈퍼 초고밀도 화면 사용(시작 관리자 아이콘만 해당, -다중 화면 지원의 -참고를 참조하십시오), 약 640dpi. API 레벨 18에서 +
  • {@code xxxhdpi}: 울트라 슈퍼 초고밀도 화면 사용(시작 관리자 아이콘만 해당, +다중 화면 지원의 +참고를 참조하십시오), 약 640dpi. API 레벨 18에서 추가되었습니다.
  • -
  • {@code nodpi}: 이것은 기기 밀도에 일치하도록 크기를 조정하고자 하지 않는 비트맵 리소스에 +
  • {@code nodpi}: 이것은 기기 밀도에 일치하도록 크기를 조정하고자 하지 않는 비트맵 리소스에 사용할 수 있습니다.
  • -
  • {@code tvdpi}: Mdpi와 hdpi 사이 어딘가에 해당되는 화면, 약 213dpi. 이것은 -"기본" 밀도 그룹으로 간주되지 않습니다. 이는 대체로 텔레비전용으로 만들어진 것이며 -대부분의 앱에는 필요하지 않는 것이 정상입니다. mdpi 및 hdpi만 제공하면 대부분의 앱에는 충분하고 +
  • {@code tvdpi}: Mdpi와 hdpi 사이 어딘가에 해당되는 화면, 약 213dpi. 이것은 +"기본" 밀도 그룹으로 간주되지 않습니다. 이는 대체로 텔레비전용으로 만들어진 것이며 +대부분의 앱에는 필요하지 않는 것이 정상입니다. mdpi 및 hdpi만 제공하면 대부분의 앱에는 충분하고 시스템이 필요에 따라 크기를 조정해줍니다. 이 한정자는 API 레벨 13과 함께 도입되었습니다.
  • -

    여섯 가지 기본 밀도간에 3:4:6:8:12:16 비율 척도가 있습니다(tvdpi 밀도는 +

    여섯 가지 기본 밀도간에 3:4:6:8:12:16 비율 척도가 있습니다(tvdpi 밀도는 무시). 그러므로 ldpi의 9x9 비트맵은 mdpi에서 12x12이고, hdpi에서 18x18, xhdpi에서 24x24 등, 이런 식으로 적용됩니다.

    -

    이미지 리소스가 텔레비전이나 특정 기기에서 제대로 보이지 않는다고 결정하고 +

    이미지 리소스가 텔레비전이나 특정 기기에서 제대로 보이지 않는다고 결정하고 tvdpi 리소스를 사용하려 할 경우, 배율은 1.33*mdpi입니다. 예를 들어, mdpi 화면의 100px x 100px 이미지는 tvdpi에서 133px x 133px가 되어야 합니다.

    -

    참고: 밀도 한정자를 사용하더라도 해당 리소스가 그 밀도의 화면 -전용이라는 뜻은 아닙니다. 현재 기기 구성과 더욱 잘 맞는 한정자가 포함된 대체 리소스를 -제공하지 않으면, +

    참고: 밀도 한정자를 사용하더라도 해당 리소스가 그 밀도의 화면 +전용이라는 뜻은 아닙니다. 현재 기기 구성과 더욱 잘 맞는 한정자가 포함된 대체 리소스를 +제공하지 않으면, 시스템이 가장 잘 일치하는 리소스를 사용합니다.

    -

    다양한 화질을 처리하는 방법과 -Android가 현재 화질에 맞춰 비트맵을 축소하는 방법에 관한 자세한 정보는 다중 화면 +

    다양한 화질을 처리하는 방법과 +Android가 현재 화질에 맞춰 비트맵을 축소하는 방법에 관한 자세한 정보는 다중 화면 지원을 참조하십시오.

    @@ -662,10 +662,10 @@ Android가 현재 화질에 맞춰 비트맵을 축소하는 방법에 관한
    @@ -678,25 +678,25 @@ Android가 현재 화질에 맞춰 비트맵을 축소하는 방법에 관한 @@ -710,13 +710,13 @@ android.content.res.Configuration#keyboardHidden}을 참조하십시오. 이 필 @@ -729,13 +729,13 @@ android.content.res.Configuration#keyboardHidden}을 참조하십시오. 이 필 @@ -749,13 +749,13 @@ android.content.res.Configuration#keyboardHidden}을 참조하십시오. 이 필 @@ -792,11 +792,11 @@ orientation" described above.

    참고: 일부 구성 한정자는 Android -1.0 이후부터 추가되었으므로 모든 Android 버전이 모든 한정자를 지원하는 것은 아닙니다. 새로운 한정자를 사용하면 암시적으로 -플랫폼 버전 한정자도 추가하므로 구형 기기가 이를 무시하게 됩니다. 예를 들어 -w600dp 한정자를 사용하면 자동적으로 v13 한정자를 포함합니다. -사용 가능한 너비 한정자가 API 레벨 13부터 새로 도입되었기 때문입니다. 문제를 애초에 피하려면, 항상 -기본 리소스를 한 세트 포함하세요(한정자 없는 리소스 한 세트). 자세한 정보는 +1.0 이후부터 추가되었으므로 모든 Android 버전이 모든 한정자를 지원하는 것은 아닙니다. 새로운 한정자를 사용하면 암시적으로 +플랫폼 버전 한정자도 추가하므로 구형 기기가 이를 무시하게 됩니다. 예를 들어 +w600dp 한정자를 사용하면 자동적으로 v13 한정자를 포함합니다. +사용 가능한 너비 한정자가 API 레벨 13부터 새로 도입되었기 때문입니다. 문제를 애초에 피하려면, 항상 +기본 리소스를 한 세트 포함하세요(한정자 없는 리소스 한 세트). 자세한 정보는 리소스와 연관된 최선의 기기 호환성 제공 을 참조하십시오.

    @@ -808,7 +808,7 @@ orientation" described above.

    • 한 가지 리소스 세트에 여러 개의 한정자를 사용할 수 있으며, 이를 대시로 구분하면 됩니다. 예를 들어, -drawable-en-rUS-land는 수평 방향의 +drawable-en-rUS-land는 수평 방향의 US-English 기기에 적용합니다.
    • 한정자는 표2에 나열된 순서를 따라야 합니다. 예: @@ -817,25 +817,25 @@ US-English 기기에 적용합니다.
    • 맞는 배열: drawable-port-hdpi/
    -
  • 대체 리소스 디렉터리는 중첩될 수 없습니다. 예를 들어, +
  • 대체 리소스 디렉터리는 중첩될 수 없습니다. 예를 들어, res/drawable/drawable-en/는 있을 수 없습니다.
  • -
  • 값은 대소문자를 구분하지 않습니다. 리소스 컴파일러가 처리 전에 디렉터리 이름을 -소문자로 바꿔 대소문자를 구분하지 않는 +
  • 값은 대소문자를 구분하지 않습니다. 리소스 컴파일러가 처리 전에 디렉터리 이름을 +소문자로 바꿔 대소문자를 구분하지 않는 파일 시스템에서 문제를 일으키지 않도록 방지합니다. 이름에 대문자가 있는 것은 오로지 가독성을 향상하기 위해서입니다.
  • -
  • 각 한정자 유형마다 한 개의 값만 지원됩니다. 예를 들어, 스페인과 프랑스에 -같은 드로어블 파일을 사용하고자 하는 경우 디렉터리 이름이 -drawable-rES-rFR/이면 안 됩니다. 대신 +
  • 각 한정자 유형마다 한 개의 값만 지원됩니다. 예를 들어, 스페인과 프랑스에 +같은 드로어블 파일을 사용하고자 하는 경우 디렉터리 이름이 +drawable-rES-rFR/이면 안 됩니다. 대신 drawable-rES/drawable-rFR/ 같이 적절한 파일이 포함된 두 개의 리소스 디렉터리가 필요합니다. -그러나 두 위치에서 같은 파일을 실제로 복제할 필요는 없습니다. 대신 +그러나 두 위치에서 같은 파일을 실제로 복제할 필요는 없습니다. 대신 리소스에 별명을 만들면 됩니다. 아래의 별명 리소스 생성을 참조하십시오.
  • -

    이런 한정자로 이름을 지은 디렉터리에 대체 리소스를 저장하고 나면 +

    이런 한정자로 이름을 지은 디렉터리에 대체 리소스를 저장하고 나면 Android가 현재 기기 구성에 기초하여 애플리케이션에 자동으로 리소스를 적용합니다. 리소스가 요청될 때마다 Android가 요청한 리소스 파일이 들어있는 -대체 리소스 디렉터리를 확인하고, 그런 다음 가장 잘 일치하는 -리소스를 찾습니다(아래에서 논함). 특정 기기 구성에 일치하는 대체 리소스가 없는 경우, +대체 리소스 디렉터리를 확인하고, 그런 다음 가장 잘 일치하는 +리소스를 찾습니다(아래에서 논함). 특정 기기 구성에 일치하는 대체 리소스가 없는 경우, Android는 상응하는 기본 리소스(구성 한정자를 포함하지 않는 특정 리소스 유형에 대한 리소스 세트 )를 사용합니다.

    @@ -844,31 +844,31 @@ Android는 상응하는 기본 리소스(구성 한정자를 포함하지 않는

    별명 리소스 생성

    -

    어떤 리소스를 하나 이상의 기기 구성에서 사용하고자 하는 경우(그렇지만 -이를 기본 리소스를 제공하는 것은 원치 않는 경우), 같은 리소스를 하나 이상의 대체 리소스 디렉터리에 -넣지 않아도 됩니다. 대신, 기본 리소스 디렉터리에 저장된 리소스에 대해 별명 역할을 하는 -대체 +

    어떤 리소스를 하나 이상의 기기 구성에서 사용하고자 하는 경우(그렇지만 +이를 기본 리소스를 제공하는 것은 원치 않는 경우), 같은 리소스를 하나 이상의 대체 리소스 디렉터리에 +넣지 않아도 됩니다. 대신, 기본 리소스 디렉터리에 저장된 리소스에 대해 별명 역할을 하는 +대체 리소스를 만들면 됩니다(경우에 따라).

    -

    참고: 모든 리소스가 다른 리소스에 대한 -별명을 생성할 수 있는 메커니즘을 제공하는 것은 아닙니다. 특히, {@code xml/} 디렉터리의 애니메이션, 메뉴, 원시 및 기타 지정되지 않은 +

    참고: 모든 리소스가 다른 리소스에 대한 +별명을 생성할 수 있는 메커니즘을 제공하는 것은 아닙니다. 특히, {@code xml/} 디렉터리의 애니메이션, 메뉴, 원시 및 기타 지정되지 않은 리소스는 이 기능을 제공하지 않습니다.

    -

    예를 들어, 애플리케이션 아이콘 {@code icon.png}이 있고 서로 다른 로케일에서 이 아이콘의 고유 버전이 -필요한 경우가 있습니다. 그러나 두 로케일, English-Canadian과 French-Canadian은 같은 버전을 -사용해야 합니다. 같은 이미지를 English-Canadian과 French-Canadian 양쪽 -모두에 대한 리소스 디렉터리에 복사해야 한다고 생각할 수 있지만, 실은 +

    예를 들어, 애플리케이션 아이콘 {@code icon.png}이 있고 서로 다른 로케일에서 이 아이콘의 고유 버전이 +필요한 경우가 있습니다. 그러나 두 로케일, English-Canadian과 French-Canadian은 같은 버전을 +사용해야 합니다. 같은 이미지를 English-Canadian과 French-Canadian 양쪽 +모두에 대한 리소스 디렉터리에 복사해야 한다고 생각할 수 있지만, 실은 그렇지 않습니다. 대신, 두 로케일에서 사용하는 이미지를 {@code icon_ca.png}( -{@code icon.png} 이외에 어떤 이름이든 가능)로 저장하고 이를 +{@code icon.png} 이외에 어떤 이름이든 가능)로 저장하고 이를 기본 {@code res/drawable/} 디렉터리에 넣으면 됩니다. 그런 다음 {@code icon.xml} 파일을 {@code icon_ca.png} 리소스를 참조하는 {@code -res/drawable-en-rCA/} 및 {@code res/drawable-fr-rCA/}로 생성합니다. 이때, {@code <bitmap>} 요소를 사용하면 됩니다. 이렇게 하면 +res/drawable-en-rCA/} 및 {@code res/drawable-fr-rCA/}로 생성합니다. 이때, {@code <bitmap>} 요소를 사용하면 됩니다. 이렇게 하면 PNG 파일 버전 하나와 그것을 가리키는 작은 XML 파일 두 개만 저장할 수 있습니다. (XML 파일 예시는 아래와 같습니다.)

    드로어블

    -

    기존 드로어블에 별명을 생성하려면 {@code <bitmap>} 요소를 사용합니다. +

    기존 드로어블에 별명을 생성하려면 {@code <bitmap>} 요소를 사용합니다. 예를 들면 다음과 같습니다.

    @@ -896,13 +896,13 @@ R.drawable.icon_ca} 리소스({@code res/drawable/}에 저장됨)의 별명인 
     

    파일을 {@code main.xml}로 저장하면, {@code R.layout.main}으로 참조할 수 있지만 실제로는 {@code R.layout.main_ltr} - 리소스의 별명인 리소스로 + 리소스의 별명인 리소스로 컴파일링됩니다.

    문자열 및 기타 단순 값

    -

    기존 문자열에 별명을 생성하려면 원하는 문자열의 리소스 ID를 +

    기존 문자열에 별명을 생성하려면 원하는 문자열의 리소스 ID를 새 문자열의 값으로 사용하면 됩니다. 예:

    @@ -915,7 +915,7 @@ R.drawable.icon_ca} 리소스({@code res/drawable/}에 저장됨)의 별명인 
     
     

    이제 {@code R.string.hi} 리소스는 {@code R.string.hello}의 별명입니다.

    -

    기타 단순 값도 같은 방식으로 +

    기타 단순 값도 같은 방식으로 동작합니다. 예를 들면 색상은 다음과 같습니다.

    @@ -931,50 +931,50 @@ R.drawable.icon_ca} 리소스({@code res/drawable/}에 저장됨)의 별명인 
     
     

    리소스와 연관된 최선의 기기 호환성 제공

    -

    애플리케이션이 여러 기기 구성을 지원하게 하려면, +

    애플리케이션이 여러 기기 구성을 지원하게 하려면, 언제나 애플리케이션이 사용하는 각 유형의 리소스에 기본 리소스를 제공하는 것이 매우 중요합니다.

    예를 들어 애플리케이션이 여러 언어를 지원할 경우, 항상 언어 및 지역 한정자 없이 {@code -values/} 디렉터리(여기에 문자열 저장)를 포함시켜야 합니다. 그렇게 하지 않고 언어와 지역 한정자가 있는 디렉터리에 -모든 문자열을 넣으면, 문자열이 지원하지 않는 언어로 설정된 기기에서 애플리케이션을 -실행하면 작동이 중단됩니다. 그러나 기본 -{@code values/} 리소스를 제공하는 한은 애플리케이션이 제대로 실행됩니다(사용자가 이해하지 못하는 +values/} 디렉터리(여기에 문자열 저장)를 포함시켜야 합니다. 그렇게 하지 않고 언어와 지역 한정자가 있는 디렉터리에 +모든 문자열을 넣으면, 문자열이 지원하지 않는 언어로 설정된 기기에서 애플리케이션을 +실행하면 작동이 중단됩니다. 그러나 기본 +{@code values/} 리소스를 제공하는 한은 애플리케이션이 제대로 실행됩니다(사용자가 이해하지 못하는 언어로라도 작동합니다. 작동 중단보다 낫습니다.)

    -

    마찬가지로 화면 방향에 기초하여 여러 가지 레이아웃 리소스를 제공하는 경우 +

    마찬가지로 화면 방향에 기초하여 여러 가지 레이아웃 리소스를 제공하는 경우 하나의 방향을 기본값으로 선택해야 합니다. 예를 들어 가로 방향에는 {@code -layout-land/}로, 세로 방향에는 {@code layout-port/}로 레이아웃 리소스를 제공하는 대신 하나를 기본으로 남겨두십시오. +layout-land/}로, 세로 방향에는 {@code layout-port/}로 레이아웃 리소스를 제공하는 대신 하나를 기본으로 남겨두십시오. 가로 방향에 {@code layout/}, 세로 방향에 {@code layout-port/}와 같은 식으로 하면 됩니다.

    -

    애플리케이션이 예상치 못한 구성에서 실행될 수 있을 뿐만 아니라 -Android의 새 버전에서 이전 버전에서는 지원하지 않는 구성 한정자를 추가할 수도 있으므로, -기본 리소스를 제공하는 것이 중요합니다. 새 리소스 한정자를 사용하지만, +

    애플리케이션이 예상치 못한 구성에서 실행될 수 있을 뿐만 아니라 +Android의 새 버전에서 이전 버전에서는 지원하지 않는 구성 한정자를 추가할 수도 있으므로, +기본 리소스를 제공하는 것이 중요합니다. 새 리소스 한정자를 사용하지만, Android 이전 버전과 코드 호환성은 유지한 경우, 그 후 Android 이전 버전이 -애플리케이션을 실행하면 새로운 한정자로 이름을 지정한 리소스를 사용할 수 없으므로 기본 리소스를 제공하지 않으면 +애플리케이션을 실행하면 새로운 한정자로 이름을 지정한 리소스를 사용할 수 없으므로 기본 리소스를 제공하지 않으면 애플리케이션 작동이 중단됩니다. 예를 들어, {@code -minSdkVersion}이 4로 설정되고 야간 모드(API 레벨 8에서 추가된 {@code night} 또는 {@code notnight})를 사용하는 모든 드로어블 리소스를 한정할 경우, API 레벨 4 기기는 -드로어블 리소스에 액세스하지 못하고 사용이 중단됩니다. 이 경우, -{@code notnight}를 기본 리소스로 제공하는 것이 좋습니다. 그래야 해당 한정자를 배제하고 +minSdkVersion}이 4로 설정되고 야간 모드(API 레벨 8에서 추가된 {@code night} 또는 {@code notnight})를 사용하는 모든 드로어블 리소스를 한정할 경우, API 레벨 4 기기는 +드로어블 리소스에 액세스하지 못하고 사용이 중단됩니다. 이 경우, +{@code notnight}를 기본 리소스로 제공하는 것이 좋습니다. 그래야 해당 한정자를 배제하고 드로어블 리소스가 {@code drawable/} 또는 {@code drawable-night/}이 됩니다.

    -

    그러므로 최선의 기기 호환성을 제공하려면 언제나 -애플리케이션에서 반드시 제대로 수행해야 하는 리소스에 대해 기본 리소스를 제공하십시오. 그런 다음 구성 한정자를 사용하여 +

    그러므로 최선의 기기 호환성을 제공하려면 언제나 +애플리케이션에서 반드시 제대로 수행해야 하는 리소스에 대해 기본 리소스를 제공하십시오. 그런 다음 구성 한정자를 사용하여 특정 기기 구성에 대해 대체 리소스를 생성하면 됩니다.

    -

    이 규칙에는 한 가지 예외가 있습니다. 애플리케이션의 {@code minSdkVersion} 이 4 이상이면 -화면 밀도 한정자로 대체 드로어블 리소스를 제공할 때 기본 드로어블 -리소스가 없어도 됩니다. 기본 -드로어블 리소스가 없더라도 Android가 대체 화면 화질 중에서 가장 잘 맞는 리소스를 찾고 -필요에 따라 비트맵을 축소합니다. 그러나 모든 유형의 기기에서 최상의 경험을 제공하려면, +

    이 규칙에는 한 가지 예외가 있습니다. 애플리케이션의 {@code minSdkVersion} 이 4 이상이면 +화면 밀도 한정자로 대체 드로어블 리소스를 제공할 때 기본 드로어블 +리소스가 없어도 됩니다. 기본 +드로어블 리소스가 없더라도 Android가 대체 화면 화질 중에서 가장 잘 맞는 리소스를 찾고 +필요에 따라 비트맵을 축소합니다. 그러나 모든 유형의 기기에서 최상의 경험을 제공하려면, 모든 세 가지 유형의 밀도에 대해 대체 드로어블을 제공해야 합니다.

    Android가 가장 잘 일치하는 리소스를 찾는 방법

    -

    개발자가 자신이 대체를 제공하는 리소스를 요청하면 Android가 런타임에 어느 대체 리소스를 -사용할지 현대 기기 구성에 따라 여러 가지로 선택합니다. Android가 -대체 리소스를 선택하는 방법을 보여주기 위해 다음 드로어블 디렉터리에 각각 같은 이미지의 +

    개발자가 자신이 대체를 제공하는 리소스를 요청하면 Android가 런타임에 어느 대체 리소스를 +사용할지 현대 기기 구성에 따라 여러 가지로 선택합니다. Android가 +대체 리소스를 선택하는 방법을 보여주기 위해 다음 드로어블 디렉터리에 각각 같은 이미지의 서로 다른 버전이 들어있다고 가정하겠습니다.

    @@ -997,16 +997,16 @@ drawable-port-notouch-12key/
     기본 텍스트 입력 메서드 = 12key
     

    -

    Android는 기기 구성을 이용 가능한 대체 리소스와 비교하여, +

    Android는 기기 구성을 이용 가능한 대체 리소스와 비교하여, {@code drawable-en-port}에서 드로어블을 선택합니다.

    -

    시스템은 다음과 같은 논리에 따라 +

    시스템은 다음과 같은 논리에 따라 어느 리소스를 사용할지 결정합니다.

    -

    그림 2. Android가 가장 잘 일치하는 리소스를 찾는 방법을 나타낸 +

    그림 2. Android가 가장 잘 일치하는 리소스를 찾는 방법을 나타낸 흐름도입니다.

    @@ -1024,23 +1024,23 @@ drawable-en-notouch-12key/ drawable-port-ldpi/ drawable-port-notouch-12key/
    -

    예외: 화면 픽셀 밀도 한정자 하나만은 충돌을 이유로 제거되지 -않습니다. 기기의 화면 밀도가 hdpi라도, +

    예외: 화면 픽셀 밀도 한정자 하나만은 충돌을 이유로 제거되지 +않습니다. 기기의 화면 밀도가 hdpi라도, 현 시점에서는 모든 화면 밀도가 일치로 간주되므로 drawable-port-ldpi/를 제거하지 않습니다. - 자세한 정보는 다중 화면 + 자세한 정보는 다중 화면 지원 문서에서 이용하실 수 있습니다.

  • 목록(표2)에서 (그 다음으로) 우선 순위가 가장 높은 한정자를 선택합니다 (MCC부터 시작하여 아래로 내려가십시오).
  • 리소스 디렉터리 중에 이 한정자를 포함한 것이 있나요?
    • -
    • 없는 경우, 2단계로 돌아가 다음 한정자를 살펴보십시오 (이 예시의 경우 +
    • 없는 경우, 2단계로 돌아가 다음 한정자를 살펴보십시오 (이 예시의 경우 언어 한정자에 도달할 때까지 답은 "없습니다"입니다).
    • 있는 경우, 4단계로 계속 진행합니다.
    -
  • 이 한정자를 포함하지 않는 디렉터리를 제거합니다. 이 예시에서는 시스템이 +
  • 이 한정자를 포함하지 않는 디렉터리를 제거합니다. 이 예시에서는 시스템이 언어 한정자를 포함하지 않는 디렉터리를 모두 제거합니다.
  •  drawable/
    @@ -1050,15 +1050,15 @@ drawable-en-notouch-12key/
     drawable-port-ldpi/
     drawable-port-notouch-12key/
     
    -

    예외: 문제의 한정자가 화면 픽셀 밀도라면, -Android는 기기 화면 밀도와 가장 가깝게 일치하는 옵션을 선택합니다. +

    예외: 문제의 한정자가 화면 픽셀 밀도라면, +Android는 기기 화면 밀도와 가장 가깝게 일치하는 옵션을 선택합니다. 일반적으로, Android는 작은 원본 이미지를 확대하는 것보다 -큰 원본 이미지를 축소하는 것을 선호합니다. 다중 화면 +큰 원본 이미지를 축소하는 것을 선호합니다. 다중 화면 지원을 참조하십시오.

    -
  • 뒤로 돌아가 디렉터리가 한 개만 남을 때까지 2, 3 및 4단계를 반복합니다. 이 예시에서, 일치하는 것이 있는 다음 한정자는 -화면 방향입니다. +
  • 뒤로 돌아가 디렉터리가 한 개만 남을 때까지 2, 3 및 4단계를 반복합니다. 이 예시에서, 일치하는 것이 있는 다음 한정자는 +화면 방향입니다. 그러므로 화면 방향을 지정하지 않는 리소스가 제거됩니다.
     drawable-en/
    @@ -1069,26 +1069,26 @@ drawable-en-port/
       
  • -

    이 절차는 요청된 각 리소스에 대해 실행하지만, 시스템이 몇 가지 측면을 추가로 -최적화합니다. 그러한 최적화 가운데에는 일단 기기 구성을 알게 되고 나면 절대 일치할 가능성이 없는 -대체 리소스를 시스템이 제거할 수 있다는 점도 있습니다. 예를 들어, 구성 언어가 -영어("en")이고 영어 이외의 다른 언어 한정자로 설정된 리소스 디렉터리는 +

    이 절차는 요청된 각 리소스에 대해 실행하지만, 시스템이 몇 가지 측면을 추가로 +최적화합니다. 그러한 최적화 가운데에는 일단 기기 구성을 알게 되고 나면 절대 일치할 가능성이 없는 +대체 리소스를 시스템이 제거할 수 있다는 점도 있습니다. 예를 들어, 구성 언어가 +영어("en")이고 영어 이외의 다른 언어 한정자로 설정된 리소스 디렉터리는 절대 확인된 리소스 풀에 포함되지 않습니다( 언어 한정자가 포함되지 않는 리소스 디렉터리는 여전히 포함됩니다).

    화면 크기 한정자에 기초하여 리소스를 선택할 때 시스템은 가장 잘 일치하는 리소스가 없다면 현재 화면보다 작은 화면에 지정된 리소스를 사용합니다 -(예를 들어, 큰 화면은 필요에 따라 일반 크기 화면 리소스를 사용합니다). 그러나 +(예를 들어, 큰 화면은 필요에 따라 일반 크기 화면 리소스를 사용합니다). 그러나 이용 가능한 리소스가 현재 화면보다 리소스뿐이라면, 시스템은 이를 사용하지 않고, 기기 구성에 일치하는 리소스가 없으면 애플리케이션 사용이 중단됩니다 (예를 들어 모든 레이아웃 리소스가 {@code xlarge} 한정자에 태그되어 있지만, 기기가 보통 크기 화면일 경우).

    -

    참고: 한정자의 우선 순위(표 2 참조)가 기기와 정확하게 일치하는 -한정자 수보다 더 중요합니다. 예를 들어 위의 4단계에서 +

    참고: 한정자의 우선 순위(표 2 참조)가 기기와 정확하게 일치하는 +한정자 수보다 더 중요합니다. 예를 들어 위의 4단계에서 목록의 마지막 선택에 기기와 정확히 일치하는 한정자가 세 개 포함되어 있지만(방향, 터치 스크린 -유형 및 입력 메서드), drawable-en에는 일치하는 매개변수가 -하나뿐입니다(언어). 다만, 언어가 이러한 다른 한정자보다 우선 순위가 높기 때문에 +유형 및 입력 메서드), drawable-en에는 일치하는 매개변수가 +하나뿐입니다(언어). 다만, 언어가 이러한 다른 한정자보다 우선 순위가 높기 때문에 drawable-port-notouch-12key는 탈락합니다.

    애플리케이션에서 리소스를 사용하는 것에 대한 자세한 정보는 리소스 액세스로 계속 진행하여 알아보십시오.

    diff --git a/docs/html-intl/intl/ko/guide/topics/resources/runtime-changes.jd b/docs/html-intl/intl/ko/guide/topics/resources/runtime-changes.jd index a5e7f5bbad883..720601fb999a3 100644 --- a/docs/html-intl/intl/ko/guide/topics/resources/runtime-changes.jd +++ b/docs/html-intl/intl/ko/guide/topics/resources/runtime-changes.jd @@ -22,41 +22,41 @@ page.tags=액티비티, 수명 주기

    몇몇 기기 구성은 런타임 중에 변경될 수 있습니다 -(예: 화면 방향, 키보드 가용성 및 언어 등). 그러한 변경이 일어나는 경우, -Android는 실행 중인 +(예: 화면 방향, 키보드 가용성 및 언어 등). 그러한 변경이 일어나는 경우, +Android는 실행 중인 {@link android.app.Activity}를 다시 시작합니다({@link android.app.Activity#onDestroy()} 호출, 뒤이어 {@link -android.app.Activity#onCreate(Bundle) onCreate()} 호출). 이런 동작은 여러분이 제공한 +android.app.Activity#onCreate(Bundle) onCreate()} 호출). 이런 동작은 여러분이 제공한 대체 리소스로 애플리케이션을 자동으로 다시 로딩함으로써 새로운 기기 구성에 애플리케이션이 적응하는 것을 돕도록 설계되었습니다(예: 다양한 화면 방향과 크기에 대한 다양한 레이아웃).

    -

    다시 시작을 적절히 처리하려면 액티비티가 정상적인 +

    다시 시작을 적절히 처리하려면 액티비티가 정상적인 액티비티 -수명 주기를 통해 이전 상태를 복원하는 것이 중요합니다. 여기에서 Android는 -{@link android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()}를 호출한 다음에 액티비티를 소멸시켜 -애플리케이션 상태에 대한 데이터를 저장할 수 있습니다. 그러면 +수명 주기를 통해 이전 상태를 복원하는 것이 중요합니다. 여기에서 Android는 +{@link android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()}를 호출한 다음에 액티비티를 소멸시켜 +애플리케이션 상태에 대한 데이터를 저장할 수 있습니다. 그러면 {@link android.app.Activity#onCreate(Bundle) onCreate()} 또는 {@link android.app.Activity#onRestoreInstanceState(Bundle) onRestoreInstanceState()} 중에 상태를 복원할 수 있습니다.

    -

    애플리케이션이 애플리케이션 상태를 그대로 유지한 채 스스로 다시 시작할 수 있는지 시험해 보려면, -구성 변경을 일으켜보아야 합니다(예를 들어 화면 방향 변경 등). 이는 애플리케이션에서 여러 가지 작업을 수행하는 -동안 해봅니다. 애플리케이션이 언제든 사용자 데이터나 상태를 손실하지 않고 -다시 시작할 수 있어야 합니다. 그래야 구성 변경과 같은 이벤트를 처리할 수 있기 때문입니다. 그렇지 않으면 -사용자가 걸려오는 전화를 받은 다음 한참 후에 애플리케이션으로 돌아오면 애플리케이션 프로세스가 이미 +

    애플리케이션이 애플리케이션 상태를 그대로 유지한 채 스스로 다시 시작할 수 있는지 시험해 보려면, +구성 변경을 일으켜보아야 합니다(예를 들어 화면 방향 변경 등). 이는 애플리케이션에서 여러 가지 작업을 수행하는 +동안 해봅니다. 애플리케이션이 언제든 사용자 데이터나 상태를 손실하지 않고 +다시 시작할 수 있어야 합니다. 그래야 구성 변경과 같은 이벤트를 처리할 수 있기 때문입니다. 그렇지 않으면 +사용자가 걸려오는 전화를 받은 다음 한참 후에 애플리케이션으로 돌아오면 애플리케이션 프로세스가 이미 소멸되어 있을 수 있습니다. 액티비티 상태를 복원하는 방법을 배우려면, 액티비티 수명 주기에 관해 읽어보십시오.

    -

    하지만, 애플리케이션을 다시 시작하고 상당량의 데이터를 복원하면 비용도 많이 들고 -불량한 사용자 환경이 만들어지는 상황에 직면할 수도 있습니다. 그러한 상황이라면, +

    하지만, 애플리케이션을 다시 시작하고 상당량의 데이터를 복원하면 비용도 많이 들고 +불량한 사용자 환경이 만들어지는 상황에 직면할 수도 있습니다. 그러한 상황이라면, 두 가지 다른 옵션이 있습니다.

    1. 구성 변경 중에 객체 보존하기 -

      구성이 변경되는 중에 액티비티가 다시 시작될 수 있게 허용하되, 액티비티의 새 인스턴스에 상태 +

      구성이 변경되는 중에 액티비티가 다시 시작될 수 있게 허용하되, 액티비티의 새 인스턴스에 상태 저장 객체를 넣습니다.

    2. 구성 변경 직접 처리하기 -

      특정 구성 변경 중에 시스템이 액티비티를 다시 시작하도록 하지 못하게 방지하되, -구성이 실제로 변경되면 콜백을 수신하도록 하여 필요에 따라 액티비티를 수동으로 업데이트할 수 +

      특정 구성 변경 중에 시스템이 액티비티를 다시 시작하도록 하지 못하게 방지하되, +구성이 실제로 변경되면 콜백을 수신하도록 하여 필요에 따라 액티비티를 수동으로 업데이트할 수 있도록 합니다.

    @@ -64,30 +64,30 @@ android.app.Activity#onRestoreInstanceState(Bundle) onRestoreInstanceState()}

    구성 변경 중에 객체 보존하기

    -

    액티비티를 다시 시작하려면 많은 수의 데이터 세트를 복구해야 하는 경우, 네트워크 연결을 -다시 설정하거나 다른 집약적 작업을 수행한 다음 완전히 다시 시작하십시오. -구성 변경 때문에 사용자 환경이 느려질 수 있습니다. 또한, 액티비티 상태를 완전히 복원하려면 +

    액티비티를 다시 시작하려면 많은 수의 데이터 세트를 복구해야 하는 경우, 네트워크 연결을 +다시 설정하거나 다른 집약적 작업을 수행한 다음 완전히 다시 시작하십시오. +구성 변경 때문에 사용자 환경이 느려질 수 있습니다. 또한, 액티비티 상태를 완전히 복원하려면 {@link android.os.Bundle}을 사용할 수도 있습니다. 이것은 시스템이 개발자 대신 {@link -android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()} 콜백으로 저장해두는 것입니다. 이것은 대형 객체(예: 비트맵)를 담도록 -디자인된 것이 아니며 이 안의 데이터는 반드시 직렬화했다가 다시 역직렬화해야 합니다. 이렇게 하면 -메모리를 아주 많이 소모할 수 있으며 구성 변경이 느려질 수 있습니다. 이와 같은 상황에서는 +android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()} 콜백으로 저장해두는 것입니다. 이것은 대형 객체(예: 비트맵)를 담도록 +디자인된 것이 아니며 이 안의 데이터는 반드시 직렬화했다가 다시 역직렬화해야 합니다. 이렇게 하면 +메모리를 아주 많이 소모할 수 있으며 구성 변경이 느려질 수 있습니다. 이와 같은 상황에서는 액티비티를 다시 초기화해야 한다는 부담을 해결하기 위해 액티비티가 구성 변경으로 인해 다시 시작되었을 때 {@link -android.app.Fragment}를 보존하면 됩니다. 이 프래그먼트에는 +android.app.Fragment}를 보존하면 됩니다. 이 프래그먼트에는 보존하고자 하는 상태 저장 객체에 대한 참조를 담을 수 있습니다.

    -

    Android 시스템이 구성 변경으로 인하여 액티비티를 종료시킬 때, 액티비티에서 보존하기로 표시해둔 -프래그먼트는 소멸되지 않습니다. 그러한 프래그먼트를 액티비티에 추가하면 +

    Android 시스템이 구성 변경으로 인하여 액티비티를 종료시킬 때, 액티비티에서 보존하기로 표시해둔 +프래그먼트는 소멸되지 않습니다. 그러한 프래그먼트를 액티비티에 추가하면 상태 저장 객체를 보존할 수 있습니다.

    런타임 구성 변경 중에 상태 저장 객체를 프래그먼트에 보존해두는 방법은 다음과 같습니다.

      -
    1. {@link android.app.Fragment} 클래스를 확장하고 상태 저장 +
    2. {@link android.app.Fragment} 클래스를 확장하고 상태 저장 객체에 참조를 선언합니다.
    3. 프래그먼트가 생성되면 {@link android.app.Fragment#setRetainInstance(boolean)}를 호출합니다.
    4. 해당 프래그먼트를 액티비티에 추가합니다.
    5. -
    6. {@link android.app.FragmentManager}를 사용하여 액티비티가 다시 시작될 때 프래그먼트를 +
    7. {@link android.app.FragmentManager}를 사용하여 액티비티가 다시 시작될 때 프래그먼트를 검색합니다.
    @@ -117,16 +117,16 @@ public class RetainedFragment extends Fragment { }
    -

    주의: 어느 객체든 저장할 수 있지만, +

    주의: 어느 객체든 저장할 수 있지만, {@link android.app.Activity}에 묶여 있는 객체는 절대로 전달하면 안 됩니다. 예를 들어 {@link android.graphics.drawable.Drawable}, {@link android.widget.Adapter}, {@link android.view.View} - 또는 {@link android.content.Context}와 연관된 기타 모든 객체가 이에 해당됩니다. 이런 것을 전달하면, -원래 액티비티 인스턴스의 모든 보기와 리소스를 몽땅 누출시킵니다. (리소스 누출이란 -애플리케이션이 리소스에 대한 보유권을 유지하고 있어 가비지 수집의 대상이 될 수 없고, 따라서 엄청난 양의 메모리가 + 또는 {@link android.content.Context}와 연관된 기타 모든 객체가 이에 해당됩니다. 이런 것을 전달하면, +원래 액티비티 인스턴스의 모든 보기와 리소스를 몽땅 누출시킵니다. (리소스 누출이란 +애플리케이션이 리소스에 대한 보유권을 유지하고 있어 가비지 수집의 대상이 될 수 없고, 따라서 엄청난 양의 메모리가 손실된다는 뜻입니다.)

    -

    그런 다음 {@link android.app.FragmentManager}를 사용하여 프래그먼트를 액티비티에 추가합니다. -프래그먼트에서 데이터 객체를 가져오려면 런타임 구성 변경 중에 액티비티가 다시 시작될 때 +

    그런 다음 {@link android.app.FragmentManager}를 사용하여 프래그먼트를 액티비티에 추가합니다. +프래그먼트에서 데이터 객체를 가져오려면 런타임 구성 변경 중에 액티비티가 다시 시작될 때 가져오면 됩니다. 예를 들어, 액티비티를 다음과 같이 정의합니다.

    @@ -165,10 +165,10 @@ public class MyActivity extends Activity {
     }
     
    -

    이 예시에서 {@link android.app.Activity#onCreate(Bundle) onCreate()}는 프래그먼트를 추가하거나 -이에 대한 참조를 복원합니다. {@link android.app.Activity#onCreate(Bundle) onCreate()} 또한 -프래그먼트 인스턴스 안에 상태 저장 객체를 저장합니다. -{@link android.app.Activity#onDestroy() onDestroy()}는 보존된 +

    이 예시에서 {@link android.app.Activity#onCreate(Bundle) onCreate()}는 프래그먼트를 추가하거나 +이에 대한 참조를 복원합니다. {@link android.app.Activity#onCreate(Bundle) onCreate()} 또한 +프래그먼트 인스턴스 안에 상태 저장 객체를 저장합니다. +{@link android.app.Activity#onDestroy() onDestroy()}는 보존된 프래그먼트 인스턴스 내부의 상태 저장 객체를 업데이트합니다.

    @@ -177,26 +177,26 @@ public class MyActivity extends Activity {

    구성 변경 직접 처리하기

    -

    애플리케이션이 특정 구성 변경 중에 리소스를 업데이트하지 않아도 되고 -그와 동시에 성능 한계가 있어 액티비티 다시 시작을 피해야 하는 경우, -액티비티가 구성 변경을 알아서 처리한다고 선언하면 됩니다. +

    애플리케이션이 특정 구성 변경 중에 리소스를 업데이트하지 않아도 되고 +그와 동시에 성능 한계가 있어 액티비티 다시 시작을 피해야 하는 경우, +액티비티가 구성 변경을 알아서 처리한다고 선언하면 됩니다. 이렇게 하면 시스템이 액티비티를 다시 시작하지 않도록 방지할 수 있습니다.

    -

    참고: 구성 변경을 직접 처리하면 대체 리소스를 사용하는 것이 -훨씬 더 까다로워질 수 있습니다. 시스템이 개발자 대신 자동으로 이를 적용해주지 않기 -때문입니다. 이 기법은 구성 변경으로 인한 재시작을 반드시 피해야만 하는 경우 최후의 수단으로서만 +

    참고: 구성 변경을 직접 처리하면 대체 리소스를 사용하는 것이 +훨씬 더 까다로워질 수 있습니다. 시스템이 개발자 대신 자동으로 이를 적용해주지 않기 +때문입니다. 이 기법은 구성 변경으로 인한 재시작을 반드시 피해야만 하는 경우 최후의 수단으로서만 고려해야 하며 대부분의 애플리케이션에는 권장하지 않습니다.

    -

    액티비티가 구성 변경을 직접 처리한다고 선언하려면, 매니페스트 파일의 적절한 {@code <activity>} 요소를 편집하여 +

    액티비티가 구성 변경을 직접 처리한다고 선언하려면, 매니페스트 파일의 적절한 {@code <activity>} 요소를 편집하여 처리하고자 하는 구성을 나타내는 값이 있는 {@code -android:configChanges} 속성을 포함하도록 +android:configChanges} 속성을 포함하도록 합니다. 가능한 값은 {@code -android:configChanges} 속성에 대한 관련 문서에 목록으로 나열되어 있습니다(가장 보편적으로 사용되는 값은 화면 방향이 변경될 때 다시 시작을 방지하는 {@code "orientation"}과 +android:configChanges} 속성에 대한 관련 문서에 목록으로 나열되어 있습니다(가장 보편적으로 사용되는 값은 화면 방향이 변경될 때 다시 시작을 방지하는 {@code "orientation"}과 키보드 가용성이 변경될 때 다시 시작을 방지하는 {@code "keyboardHidden"} -입니다). 이 속성에는 여러 개의 구성 값을 선언할 수 있습니다. 각각을 +입니다). 이 속성에는 여러 개의 구성 값을 선언할 수 있습니다. 각각을 파이프 {@code |} 문자로 구분하면 됩니다.

    -

    예를 들어 다음 매니페스트 코드는 화면 방향 변경과 키보드 가용성 변경을 둘 다 +

    예를 들어 다음 매니페스트 코드는 화면 방향 변경과 키보드 가용성 변경을 둘 다 처리하는 액티비티를 선언하는 것입니다.

    @@ -205,29 +205,29 @@ android:configChanges} 속성에 대한 관련 문서에 목록으로 나열
               android:label="@string/app_name">
     
    -

    이제 이러한 구성 중 하나가 변경되어도 {@code MyActivity}는 다시 시작하지 않습니다. +

    이제 이러한 구성 중 하나가 변경되어도 {@code MyActivity}는 다시 시작하지 않습니다. 그 대신, {@code MyActivity}가 {@link -android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}로의 호출을 받습니다. 이 메서드는 -{@link android.content.res.Configuration} 객체로 전달되며, 이는 새 기기 구성을 -나타냅니다. {@link android.content.res.Configuration}의 필드를 읽어보면 -새 구성을 판별할 수 있고 적절한 변경을 할 수 있습니다. 그러려면 인터페이스에 사용된 리소스를 -업데이트하면 됩니다. 이 메서드가 -호출되면, 액티비티의 {@link android.content.res.Resources} 객체가 -업데이트되어 새 구성에 기반한 리소스를 반환하며, 따라서 시스템이 액티비티를 다시 시작하지 않아도 +android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}로의 호출을 받습니다. 이 메서드는 +{@link android.content.res.Configuration} 객체로 전달되며, 이는 새 기기 구성을 +나타냅니다. {@link android.content.res.Configuration}의 필드를 읽어보면 +새 구성을 판별할 수 있고 적절한 변경을 할 수 있습니다. 그러려면 인터페이스에 사용된 리소스를 +업데이트하면 됩니다. 이 메서드가 +호출되면, 액티비티의 {@link android.content.res.Resources} 객체가 +업데이트되어 새 구성에 기반한 리소스를 반환하며, 따라서 시스템이 액티비티를 다시 시작하지 않아도 UI의 요소를 손쉽게 재설정할 수 있게 됩니다.

    -

    주의: Android 3.2(API 레벨 13)부터 기기가 -세로 방향 및 가로 방향 사이를 전환할 때 "화면 크기"도 -같이 변경됩니다. 따라서, +

    주의: Android 3.2(API 레벨 13)부터 기기가 +세로 방향 및 가로 방향 사이를 전환할 때 "화면 크기"도 +같이 변경됩니다. 따라서, API 레벨 13 이상({@code minSdkVersion}{@code targetSdkVersion} 속성에서 선언한 내용에 따름)을 대상으로 개발하는 경우 방향 변경으로 인한 런타임 다시 시작을 방지하고자 하면, {@code "orientation"} 값 외에 {@code "screenSize"} 값도 포함시켜야 합니다. 다시 말해, {@code -android:configChanges="orientation|screenSize"}를 선언해야 합니다. 하지만, 애플리케이션이 API 레벨 12 이하를 -대상으로 하는 경우라면 애플리케이션이 언제든 이 구성 변경을 알아서 처리합니다(이 구성 변경은 +android:configChanges="orientation|screenSize"}를 선언해야 합니다. 하지만, 애플리케이션이 API 레벨 12 이하를 +대상으로 하는 경우라면 애플리케이션이 언제든 이 구성 변경을 알아서 처리합니다(이 구성 변경은 액티비티를 다시 시작하지 않습니다. 이는 Android 3.2 이상 기기에서 실행되는 경우에도 마찬가지입니다).

    예를 들어, 다음 {@link -android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()} 구현은 +android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()} 구현은 현재 기기의 방향을 확인합니다.

    @@ -244,36 +244,36 @@ public void onConfigurationChanged(Configuration newConfig) {
     }
     
    -

    {@link android.content.res.Configuration} 객체는 변경된 것만이 아니라 현재 -구성 전체를 나타냅니다. 대부분의 경우에는 구성이 정확히 어떻게 -변경되었는지에는 관심이 없고 처리 중인 구성에 대체 리소스를 제공하는 모든 리소스를 그저 +

    {@link android.content.res.Configuration} 객체는 변경된 것만이 아니라 현재 +구성 전체를 나타냅니다. 대부분의 경우에는 구성이 정확히 어떻게 +변경되었는지에는 관심이 없고 처리 중인 구성에 대체 리소스를 제공하는 모든 리소스를 그저 재할당하기만 하면 됩니다. 예를 들어 이제 {@link android.content.res.Resources} 객체가 업데이트되었으니 {@link android.widget.ImageView#setImageResource(int) -setImageResource()}가 있는 모든 -{@link android.widget.ImageView}와 +setImageResource()}가 있는 모든 +{@link android.widget.ImageView}와 새 구성에 대한 적절한 리소스를 재설정할 수 있습니다(리소스 제공에 설명된 바와 같음).

    {@link -android.content.res.Configuration} 필드에서 가져온 값이 -{@link android.content.res.Configuration} 클래스에서 가져온 특정 상수와 일치하는 정수라는 점을 눈여겨 보십시오. 각 필드에 +android.content.res.Configuration} 필드에서 가져온 값이 +{@link android.content.res.Configuration} 클래스에서 가져온 특정 상수와 일치하는 정수라는 점을 눈여겨 보십시오. 각 필드에 어느 상수를 써야 하는지에 대한 관련 문서는 {@link android.content.res.Configuration} 참조에 있는 적절한 필드를 참조하십시오.

    -

    명심할 점: 액티비티가 직접 구성 변경을 처리한다고 선언하는 경우, -대체를 제공하는 모든 요소에 대해 본인이 직접 책임을 지게 됩니다. 액티비티가 직접 -방향 변경을 처리하고 가로 및 세로 방향 사이에서 바뀌어야 하는 이미지가 있는 경우, +

    명심할 점: 액티비티가 직접 구성 변경을 처리한다고 선언하는 경우, +대체를 제공하는 모든 요소에 대해 본인이 직접 책임을 지게 됩니다. 액티비티가 직접 +방향 변경을 처리하고 가로 및 세로 방향 사이에서 바뀌어야 하는 이미지가 있는 경우, 각 리소스를 각 요소에 재할당해야 하며 이를 {@link android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()} 중에 수행해야 합니다.

    -

    이러한 구성 변경을 기반으로 애플리케이션을 업데이트하지 않아도 되는 경우, +

    이러한 구성 변경을 기반으로 애플리케이션을 업데이트하지 않아도 되는 경우, 대신 {@link -android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}를 구현하지 않으면 됩니다. 이런 -경우, 구성 변경 전에 쓰였던 리소스가 모두 그대로 사용되고 액티비티의 다시 시작만 -피한 것이 됩니다. 그러나, 애플리케이션은 -언제든 종료되고 이전 상태를 그대로 유지한 채 다시 시작될 수 있어야 합니다 정상적인 액티비티 -수명 주기 중에 상태 유지에서의 탈출 방안으로 이 기법을 고려해서는 안 됩니다. 이는 애플리케이션이 -다시 시작되지 않도록 방지할 수 없는, 다른 구성 변경도 여럿 있어서일뿐만 아니라, 사용자가 -애플리케이션을 떠났을 경우 해당 사용자가 다시 돌아오기 전에 소멸되는 것과 같은 이벤트를 처리해야 하기 때문이라는 +android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}를 구현하지 않으면 됩니다. 이런 +경우, 구성 변경 전에 쓰였던 리소스가 모두 그대로 사용되고 액티비티의 다시 시작만 +피한 것이 됩니다. 그러나, 애플리케이션은 +언제든 종료되고 이전 상태를 그대로 유지한 채 다시 시작될 수 있어야 합니다 정상적인 액티비티 +수명 주기 중에 상태 유지에서의 탈출 방안으로 이 기법을 고려해서는 안 됩니다. 이는 애플리케이션이 +다시 시작되지 않도록 방지할 수 없는, 다른 구성 변경도 여럿 있어서일뿐만 아니라, 사용자가 +애플리케이션을 떠났을 경우 해당 사용자가 다시 돌아오기 전에 소멸되는 것과 같은 이벤트를 처리해야 하기 때문이라는 이유도 있습니다.

    액티비티 내에서 처리할 수 있는 구성 변경이 무엇인지에 대한 자세한 내용은 {@code diff --git a/docs/html-intl/intl/ko/guide/topics/ui/controls.jd b/docs/html-intl/intl/ko/guide/topics/ui/controls.jd index bf873980beb6a..9561ba05771ba 100644 --- a/docs/html-intl/intl/ko/guide/topics/ui/controls.jd +++ b/docs/html-intl/intl/ko/guide/topics/ui/controls.jd @@ -7,11 +7,11 @@ parent.link=index.html -

    입력 제어는 앱의 사용자 인터페이스에 있는 대화형 구성 요소입니다. +

    입력 제어는 앱의 사용자 인터페이스에 있는 대화형 구성 요소입니다. Android는 버튼, 텍스트 필드, 찾기 막대, 확인란, 확대 버튼, 전환 버튼 등과 같이 UI에서 사용할 수 있도록 매우 다양한 제어를 제공합니다.

    -

    UI에 입력 제어를 추가하려면 단순히 XML 레이아웃에 XML 요소를 하나 추가하기만 하면 됩니다. +

    UI에 입력 제어를 추가하려면 단순히 XML 레이아웃에 XML 요소를 하나 추가하기만 하면 됩니다. 다음은 텍스트 필드와 버튼이 있는 레이아웃을 예시로 나타낸 것입니다.

    @@ -33,16 +33,16 @@ UI에서 사용할 수 있도록 매우 다양한 제어를 제공합니다.

    </LinearLayout>
    -

    각 입력 제어는 특정한 입력 이벤트를 지원하므로, 사용자가 텍스트를 입력할 때 또는 버튼을 터치할 때 +

    각 입력 제어는 특정한 입력 이벤트를 지원하므로, 사용자가 텍스트를 입력할 때 또는 버튼을 터치할 때 이벤트를 처리할 수 있게 해줍니다.

    보편적인 제어

    -

    다음은 앱에서 사용할 수 있는 몇 가지 보편적인 제어를 목록으로 나열한 것입니다. 링크를 따라가면 각 제어에 대해 +

    다음은 앱에서 사용할 수 있는 몇 가지 보편적인 제어를 목록으로 나열한 것입니다. 링크를 따라가면 각 제어에 대해 좀 더 자세히 알아볼 수 있습니다.

    참고: Android는 여기에 나열된 것보다 몇 가지 더 많은 제어를 제공합니다. - 더 많은 내용을 알아보려면 {@link android.widget} 패키지를 탐색해보십시오. + 더 많은 내용을 알아보려면 {@link android.widget} 패키지를 탐색해보십시오. 앱에 특정한 종류의 입력 제어가 필요한 경우, 나름의 사용자 지정 구성 요소를 직접 구축해도 됩니다.

    -

    이동통신 국가 코드(MCC)에 선택적으로 이동통신 네트워크 코드(MNC)가 이어지는 형태로, +

    이동통신 국가 코드(MCC)에 선택적으로 이동통신 네트워크 코드(MNC)가 이어지는 형태로, 기기의 SIM 카드에서 가져옵니다. 예를 들어, mcc310은 모든 이동통신사를 포함한 미국이고, mcc310-mnc004는 Verizon을 사용하는 미국, mcc208-mnc00은 Orange를 사용하는 프랑스입니다.

    @@ -293,11 +293,11 @@ background.png} 이미지를 참조하는 데 사용하는 리소스 ID는 항 SIM 카드에서 가져옵니다.

    MCC만 단독으로 사용할 수도 있습니다(예를 들어, 애플리케이션에 국가별 합법적 리소스를 포함하는 경우). 언어에 기초해서만 지정해야 할 경우, -언어 및 지역 한정자를 대신 사용합니다(아래에 설명). MCC와 +언어 및 지역 한정자를 대신 사용합니다(아래에 설명). MCC와 MNC 한정자를 사용할 경우, 조심해서 사용하고 예상한 대로 작동하는지 테스트해야 합니다.

    또한, 구성 필드 {@link android.content.res.Configuration#mcc}와 {@link -android.content.res.Configuration#mnc}를 참조하십시오. 이 구성 필드는 각각 이동통신 국가 코드와 +android.content.res.Configuration#mnc}를 참조하십시오. 이 구성 필드는 각각 이동통신 국가 코드와 이동통신 네트워크 코드를 나타냅니다.

    언어는 두 글자의 ISO -639-1 언어 코드로 정의되고, +639-1 언어 코드로 정의되고, 뒤이어 두 글자의 ISO 3166-1-alpha-2 지역 코드가 선택적으로 따라옵니다(소문자 "{@code r}" 뒤에 붙음).

    - 코드는 대소문자를 구별하지 않습니다. {@code r} 접두사는 + 코드는 대소문자를 구별하지 않습니다. {@code r} 접두사는 지역 부분을 구별하기 위해 사용합니다. 지역만 지정할 수는 없습니다.

    -

    사용자가 시스템 설정에서 언어를 변경할 경우 +

    사용자가 시스템 설정에서 언어를 변경할 경우 애플리케이션 수명 중에 변경될 수 있습니다. 런타임에서 애플리케이션에 어떤 영향을 미치는지 자세히 알아보려면 런타임 변경 처리를 참조하십시오.

    다른 여러 언어에 맞게 애플리케이션을 지역화하기 위한 전체 지침은 지역화를 참조하십시오.

    -

    또한, 현재 로케일을 나타내는 {@link android.content.res.Configuration#locale} 구성 필드도 +

    또한, 현재 로케일을 나타내는 {@link android.content.res.Configuration#locale} 구성 필드도 참조하십시오.

    -

    리소스를 사용해야 하는 {@code dp} 단위에서 최소 이용 가능한 화면 너비를 지정합니다. -이는 <N> 값이 정의합니다. 이 구성 -값은 현재 실제 너비에 맞추기 위해 화면 방향이 가로와 세로 사이를 오가며 바뀔 때 +

    리소스를 사용해야 하는 {@code dp} 단위에서 최소 이용 가능한 화면 너비를 지정합니다. +이는 <N> 값이 정의합니다. 이 구성 +값은 현재 실제 너비에 맞추기 위해 화면 방향이 가로와 세로 사이를 오가며 바뀔 때 변경됩니다.

    애플리케이션이 이 구성에 대해 서로 다른 값이 포함된 여러 개의 리소스 디렉터리를 제공하면, -시스템은 기기의 현재 화면 너비에 가장 가까운(그러나 이를 초과하지 않는) -값을 사용합니다. 이 값은 -화면 장식을 감안한 것이므로, 기기의 왼쪽이나 오른쪽 가장자리에 -영구 UI 요소가 있을 경우, 기기는 +시스템은 기기의 현재 화면 너비에 가장 가까운(그러나 이를 초과하지 않는) +값을 사용합니다. 이 값은 +화면 장식을 감안한 것이므로, 기기의 왼쪽이나 오른쪽 가장자리에 +영구 UI 요소가 있을 경우, 기기는 이러한 UI 요소를 감안하여 애플리케이션의 이용 가능한 공간을 줄여서 실제 화면 크기보다 작은 너비 값을 사용합니다.

    API 레벨 13에서 추가되었습니다.

    현재 화면 너비를 보유한 {@link android.content.res.Configuration#screenWidthDp} 구성 필드도 참조하십시오.

    -

    여러 가지 화면에 맞는 디자인과 한정자 사용에 관한 자세한 정보는 +

    여러 가지 화면에 맞는 디자인과 한정자 사용에 관한 자세한 정보는 다중 화면 지원 개발자 가이드를 참조하십시오.

    -

    리소스가 사용되어야 하는 최소한의 사용 가능한 화면 높이를 "dp" 단위로 나타냅니다. -이는 <N> 값이 정의합니다. 이 구성 -값은 현재 실제 높이에 맞추기 위해 화면 방향이 가로와 세로 사이를 오가며 바뀔 때 +

    리소스가 사용되어야 하는 최소한의 사용 가능한 화면 높이를 "dp" 단위로 나타냅니다. +이는 <N> 값이 정의합니다. 이 구성 +값은 현재 실제 높이에 맞추기 위해 화면 방향이 가로와 세로 사이를 오가며 바뀔 때 변경됩니다.

    애플리케이션이 이 구성에 대해 서로 다른 값이 포함된 여러 개의 리소스 디렉터리를 제공하면, -시스템은 기기의 현재 화면 높이에 가장 가까운(그러나 이를 초과하지 않는) -값을 사용합니다. 이 값은 -화면 장식을 감안한 것이므로, 기기의 상단이나 하단 가장자리에 -영구 UI 요소가 있을 경우, 기기는 +시스템은 기기의 현재 화면 높이에 가장 가까운(그러나 이를 초과하지 않는) +값을 사용합니다. 이 값은 +화면 장식을 감안한 것이므로, 기기의 상단이나 하단 가장자리에 +영구 UI 요소가 있을 경우, 기기는 이러한 UI 요소를 감안하여 애플리케이션의 이용 가능한 공간을 줄여서 - 실제 화면 크기보다 작은 높이 값을 사용합니다. -상태 표시줄에 고정되지 않은 화면 장식(예를 들어 -전화 상태 표시줄은 전체 화면에서 숨길 수 있음)은 여기에서 감안하지 않았고, -제목 표시줄이나 작업 모음 등의 창 장식도 감안되지 않았으므로, 애플리케이션 입장에서는 자신이 지정한 것보다 어느 정도 작은 공간을 + 실제 화면 크기보다 작은 높이 값을 사용합니다. +상태 표시줄에 고정되지 않은 화면 장식(예를 들어 +전화 상태 표시줄은 전체 화면에서 숨길 수 있음)은 여기에서 감안하지 않았고, +제목 표시줄이나 작업 모음 등의 창 장식도 감안되지 않았으므로, 애플리케이션 입장에서는 자신이 지정한 것보다 어느 정도 작은 공간을 받아들일 대비를 해야 합니다.

    API 레벨 13에서 추가되었습니다.

    현재 화면 너비를 보유한 {@link android.content.res.Configuration#screenHeightDp} 구성 필드도 참조하십시오.

    -

    여러 가지 화면에 맞는 디자인과 한정자 사용에 관한 자세한 정보는 +

    여러 가지 화면에 맞는 디자인과 한정자 사용에 관한 자세한 정보는 다중 화면 지원 개발자 가이드를 참조하십시오.

      -
    • {@code small}: 저밀도 QVGA 화면과 비슷한 +
    • {@code small}: 저밀도 QVGA 화면과 비슷한 크기의 화면입니다. 작은 화면의 최소 레이아웃 크기는 -약 320x426 dp단위입니다. 이 화면의 예시로는 QVGA 저밀도 및 VGA 고밀도가 +약 320x426 dp단위입니다. 이 화면의 예시로는 QVGA 저밀도 및 VGA 고밀도가 있습니다.
    • -
    • {@code normal}: 중밀도 HVGA 화면과 +
    • {@code normal}: 중밀도 HVGA 화면과 비슷한 크기의 화면입니다. 정상 화면의 - 최소 레이아웃 크기는 약 320x470 dp 단위입니다. 이 화면의 예로는 + 최소 레이아웃 크기는 약 320x470 dp 단위입니다. 이 화면의 예로는 WQVGA 저밀도, HVGA 중밀도, WVGA 고밀도 등이 있습니다.
    • -
    • {@code large}: 중밀도 VGA 화면과 +
    • {@code large}: 중밀도 VGA 화면과 비슷한 크기의 화면입니다. 큰 화면의 최소 레이아웃 크기는 약 480x640 dp 단위입니다. 이 화면의 예시로는 VGA 및 WVGA 중밀도 화면이 있습니다.
    • -
    • {@code xlarge}: 일반적인 중밀도 HVGA 화면보다 상당히 큰 화면을 +
    • {@code xlarge}: 일반적인 중밀도 HVGA 화면보다 상당히 큰 화면을 말합니다. 초대형 화면의 - 최소 레이아웃 크기는 약 720x960 dp 단위입니다. 대부분의 경우, 초대형 화면 기기는 -주머니에 넣어 다니기에 너무 큽니다. 따라서 태블릿 스타일의 기기일 가능성이 + 최소 레이아웃 크기는 약 720x960 dp 단위입니다. 대부분의 경우, 초대형 화면 기기는 +주머니에 넣어 다니기에 너무 큽니다. 따라서 태블릿 스타일의 기기일 가능성이 높습니다. API 레벨 9에서 추가되었습니다.
    -

    참고: 크기 한정자를 사용하더라도 해당 리소스가 그 크기의 화면 -전용이라는 뜻은 아닙니다. 현재 기기 구성과 더욱 잘 맞는 한정자가 포함된 대체 리소스를 -제공하지 않으면, +

    참고: 크기 한정자를 사용하더라도 해당 리소스가 그 크기의 화면 +전용이라는 뜻은 아닙니다. 현재 기기 구성과 더욱 잘 맞는 한정자가 포함된 대체 리소스를 +제공하지 않으면, 시스템이 가장 잘 일치하는 리소스를 사용합니다.

    주의: 모든 리소스가 현재 화면보다 크기 한정자를 사용하는 경우, 시스템은 리소스를 사용하지 않으며 애플리케이션은 런타임에 작동이 중단됩니다(예를 들어, 모든 레이아웃 리소스에 {@code xlarge} 한정자가 태그되어 있지만 기기는 일반 크기 화면일 경우 ).

    API 레벨 4에서 추가되었습니다.

    - -

    자세한 정보는 다중 화면 + +

    자세한 정보는 다중 화면 지원을 참조하십시오.

    -

    {@link android.content.res.Configuration#screenLayout} 구성 필드도 참조하십시오. -이것은 화면이 소형, 일반 크기 또는 +

    {@link android.content.res.Configuration#screenLayout} 구성 필드도 참조하십시오. +이것은 화면이 소형, 일반 크기 또는 대형인지를 나타냅니다.

    • {@code notouch}: 기기에 터치 스크린이 없습니다.
    • -
    • {@code finger}: 기기에 터치 스크린이 있으며 이를 +
    • {@code finger}: 기기에 터치 스크린이 있으며 이를 사용자의 손가락을 사용한 방향 지시 상호 작용을 통해 쓰도록 되어 있습니다.
    -

    {@link android.content.res.Configuration#touchscreen} 구성 필드도 참조하십시오. +

    {@link android.content.res.Configuration#touchscreen} 구성 필드도 참조하십시오. 이는 기기에서 사용되는 터치 스크린의 유형을 나타냅니다.

      -
    • {@code keysexposed}: 기기에서 키보드를 사용할 수 있습니다. 키보드에 -소프트웨어 키보드가 활성화되어 있으면(이럴 가능성이 큽니다), 하드웨어 키보드가 사용자에게 노출되어 있지 -않거나 기기에 하드웨어 키보드가 없더라도 이 리소스를 사용할 수 있습니다. 소프트웨어 -키보드가 제공되어 있지 않거나 비활성화되어 있는 경우 이것은 하드웨어 키보드가 노출되어 있을 때에만 +
    • {@code keysexposed}: 기기에서 키보드를 사용할 수 있습니다. 키보드에 +소프트웨어 키보드가 활성화되어 있으면(이럴 가능성이 큽니다), 하드웨어 키보드가 사용자에게 노출되어 있지 +않거나 기기에 하드웨어 키보드가 없더라도 이 리소스를 사용할 수 있습니다. 소프트웨어 +키보드가 제공되어 있지 않거나 비활성화되어 있는 경우 이것은 하드웨어 키보드가 노출되어 있을 때에만 사용할 수 있습니다.
    • -
    • {@code keyshidden}: 기기에서 하드웨어 키보드를 사용할 수 있지만 +
    • {@code keyshidden}: 기기에서 하드웨어 키보드를 사용할 수 있지만 숨겨져 있고 이에 더하여 기기에 소프트웨어 키보드가 활성화되어 있지 않습니다.
    • -
    • {@code keyssoft}: 기기에 활성화된 소프트웨어 키보드가 있습니다(표시 여부는 +
    • {@code keyssoft}: 기기에 활성화된 소프트웨어 키보드가 있습니다(표시 여부는 무관).

    keysexposed 리소스를 제공하지만 keyssoft -리소스는 제공하지 않는다면, 시스템은 소프트웨어 키보드가 활성화되어 있는 동안은 키보드가 보이는지 여부와 관계없이 keysexposed +리소스는 제공하지 않는다면, 시스템은 소프트웨어 키보드가 활성화되어 있는 동안은 키보드가 보이는지 여부와 관계없이 keysexposed 리소스를 사용합니다.

    -

    이것은 사용자가 하드웨어 키보드를 여는 경우 애플리케이션 수명 중에 -변경될 수 있습니다. 이것이 런타임에 애플리케이션에 어떤 영향을 미치는지 알아보려면 런타임 변경 처리를 +

    이것은 사용자가 하드웨어 키보드를 여는 경우 애플리케이션 수명 중에 +변경될 수 있습니다. 이것이 런타임에 애플리케이션에 어떤 영향을 미치는지 알아보려면 런타임 변경 처리를 참조하십시오.

    또한, 구성 필드 {@link android.content.res.Configuration#hardKeyboardHidden}과 {@link -android.content.res.Configuration#keyboardHidden}을 참조하십시오. 이 필드는 각각 하드웨어 키보드의 가시성과 +android.content.res.Configuration#keyboardHidden}을 참조하십시오. 이 필드는 각각 하드웨어 키보드의 가시성과 모든 종류의 키보드(소프트웨어 포함)의 가시성을 나타냅니다.

    • {@code nokeys}: 기기에 텍스트 입력을 위한 하드웨어 키가 없습니다.
    • -
    • {@code qwerty}: 기기에 하드웨어 쿼티 키보드가 있습니다(이것이 +
    • {@code qwerty}: 기기에 하드웨어 쿼티 키보드가 있습니다(이것이 사용자 에게 표시되는지 여부는 무관).
    • -
    • {@code 12key}: 기기에 하드웨어 12-키 키보드가 있습니다(이것이 사용자에게 표시되는지 여부는 +
    • {@code 12key}: 기기에 하드웨어 12-키 키보드가 있습니다(이것이 사용자에게 표시되는지 여부는 무관).
    -

    {@link android.content.res.Configuration#keyboard} 구성 필드도 참조하십시오. +

    {@link android.content.res.Configuration#keyboard} 구성 필드도 참조하십시오. 이는 기본 텍스트 입력 메서드를 사용할 수 있는지 여부를 나타냅니다.

    • {@code navexposed}: 사용자가 탐색 키를 사용할 수 있습니다.
    • -
    • {@code navhidden}: 탐색 키를 사용할 수 없습니다(예: 닫힌 뚜껑 뒤에 있는 +
    • {@code navhidden}: 탐색 키를 사용할 수 없습니다(예: 닫힌 뚜껑 뒤에 있는 경우).
    -

    이것은 사용자가 탐색 키를 드러내는 경우 애플리케이션 수명 중에 -변경될 수 있습니다. 이것이 런타임에 애플리케이션에 어떤 영향을 미치는지 알아보려면 런타임 변경 처리를 +

    이것은 사용자가 탐색 키를 드러내는 경우 애플리케이션 수명 중에 +변경될 수 있습니다. 이것이 런타임에 애플리케이션에 어떤 영향을 미치는지 알아보려면 런타임 변경 처리를 참조하십시오.

    -

    {@link android.content.res.Configuration#navigationHidden} 구성 +

    {@link android.content.res.Configuration#navigationHidden} 구성 필드도 참조하십시오. 이는 탐색 키가 숨겨져 있는지 여부를 나타냅니다.

      -
    • {@code nonav}: 기기에 터치 스크린을 제외하고 다른 탐색 기능이 +
    • {@code nonav}: 기기에 터치 스크린을 제외하고 다른 탐색 기능이 없습니다.
    • {@code dpad}: 기기에 탐색용 방향 패드(d-pad)가 있습니다.
    • {@code trackball}: 기기에 탐색용 트랙볼이 있습니다.
    • {@code wheel}: 기기에 탐색용 방향 휠이 있습니다.
    -

    {@link android.content.res.Configuration#navigation} 구성 필드도 참조하십시오. +

    {@link android.content.res.Configuration#navigation} 구성 필드도 참조하십시오. 이는 사용 가능한 탐색 메서드의 유형을 나타냅니다.

    @@ -69,7 +69,7 @@ UI에서 사용할 수 있도록 매우 다양한 제어를 제공합니다.

    - diff --git a/docs/html-intl/intl/ko/guide/topics/ui/declaring-layout.jd b/docs/html-intl/intl/ko/guide/topics/ui/declaring-layout.jd index 78832368b2224..97f9083d6a571 100644 --- a/docs/html-intl/intl/ko/guide/topics/ui/declaring-layout.jd +++ b/docs/html-intl/intl/ko/guide/topics/ui/declaring-layout.jd @@ -34,14 +34,14 @@ page.tags=view,viewgroup

    참고 항목

      -
    1. 간단한 사용자 +
    2. 간단한 사용자 인터페이스 구축
    3. 레이아웃은 사용자 인터페이스에 대한 시각적 구조를 정의합니다. 예컨대 액티비티 또는 앱 위젯에 대한 UI가 이에 해당됩니다. 레이아웃을 선언하는 데에는 다음과 같은 두 가지 방법이 있습니다.

        -
      • UI 요소를 XML로 선언. Android가 위젯과 레이아웃 등과 같이 +
      • UI 요소를 XML로 선언. Android가 위젯과 레이아웃 등과 같이 보기 클래스와 하위 클래스에 상응하는 간단한 XML 어휘를 제공합니다.
      • 런타임에 레이아웃 요소를 인스턴트화. 애플리케이션이 프로그래밍 방법으로 보기 및 ViewGroup객체를 만들 수 있습니다(그리고 그 속성을 조작하기도 합니다).
      • @@ -55,26 +55,26 @@ page.tags=view,viewgroup
      • Eclipse용 ADT 플러그인이 XML의 레이아웃 미리보기를 제공합니다. — XML 파일이 열린 상태에서 레이아웃 탭을 선택하십시오.
      • -
      • 또한, -계층 뷰어 도구로 -레이아웃 디버깅도 시도해 보아야 합니다.—이것은 레이아웃 속성 값을 드러내고, -내부 여백/여백 표시기가 있는 와이어프레임을 그리며 개발자가 에뮬레이터 또는 기기에서 디버깅하는 동안 +
      • 또한, +계층 뷰어 도구로 +레이아웃 디버깅도 시도해 보아야 합니다.—이것은 레이아웃 속성 값을 드러내고, +내부 여백/여백 표시기가 있는 와이어프레임을 그리며 개발자가 에뮬레이터 또는 기기에서 디버깅하는 동안 완전히 렌더링된 보기를 제공합니다.
      • layoutopt 도구를 사용하면 레이아웃과 계층을 비효율성 또는 다른 문제에 대하여 재빨리 분석할 수 있게 해줍니다.
      • -

        UI를 XML로 선언하는 것의 이점은 이렇게 하면 애플리케이션을 그 행동을 제어하는 코드로부터 따로 표시하기가 더 좋다는 것입니다. UI 설명은 애플리케이션 코드의 외부에 있습니다. 이는 다시 말해 소스 코드를 수정하고 다시 컴파일링하지 않아도 이를 수정 또는 변경할 수 있다는 뜻입니다. 예를 들어, 서로 다른 화면 방향, 사로 다른 기기 화면 크기 및 서로 다른 언어에 대해 XML 레이아웃을 생성할 수 있습니다. 이외에도 레이아웃을 XML로 선언하면 UI의 구조를 시각화하기가 더 쉬우므로 문제를 디버깅하기도 더 쉽습니다. 따라서, 이 문서는 레이아웃을 XML로 선언하는 방법을 가르치는 데 주안점을 두고 있습니다. 런타임에 보기 객체를 인스턴트화하는 것에 흥미가 있는 경우, -{@link android.view.ViewGroup} 및 +

        UI를 XML로 선언하는 것의 이점은 이렇게 하면 애플리케이션을 그 행동을 제어하는 코드로부터 따로 표시하기가 더 좋다는 것입니다. UI 설명은 애플리케이션 코드의 외부에 있습니다. 이는 다시 말해 소스 코드를 수정하고 다시 컴파일링하지 않아도 이를 수정 또는 변경할 수 있다는 뜻입니다. 예를 들어, 서로 다른 화면 방향, 사로 다른 기기 화면 크기 및 서로 다른 언어에 대해 XML 레이아웃을 생성할 수 있습니다. 이외에도 레이아웃을 XML로 선언하면 UI의 구조를 시각화하기가 더 쉬우므로 문제를 디버깅하기도 더 쉽습니다. 따라서, 이 문서는 레이아웃을 XML로 선언하는 방법을 가르치는 데 주안점을 두고 있습니다. 런타임에 보기 객체를 인스턴트화하는 것에 흥미가 있는 경우, +{@link android.view.ViewGroup} 및 {@link android.view.View} 클래스 참조를 참조하십시오.

        -

        일반적으로 UI 요소를 선언하는 데 쓰이는 XML 어휘는 클래스와 메서드 명명을 충실히 따릅니다. 여기에서 요소 이름은 클래스 이름에 상응하며 속성 이름은 메서드에 상응합니다. 사실 이러한 일치성은 아주 직접적인 경우가 잦아 어느 XML 속성이 클래스 메서드에 상응하는지를 추측할 수 있고, 어느 클래스가 주어진 XML 요소에 상응하는지도 추측할 수 있습니다. 다만 모든 어휘가 다 같지는 않다는 점을 유의하십시오. 몇몇 경우에는 명명에 약간의 차이점이 있습니다. 예를 들어, -EditText 요소에는 text 속성이 있으며 이는 +

        일반적으로 UI 요소를 선언하는 데 쓰이는 XML 어휘는 클래스와 메서드 명명을 충실히 따릅니다. 여기에서 요소 이름은 클래스 이름에 상응하며 속성 이름은 메서드에 상응합니다. 사실 이러한 일치성은 아주 직접적인 경우가 잦아 어느 XML 속성이 클래스 메서드에 상응하는지를 추측할 수 있고, 어느 클래스가 주어진 XML 요소에 상응하는지도 추측할 수 있습니다. 다만 모든 어휘가 다 같지는 않다는 점을 유의하십시오. 몇몇 경우에는 명명에 약간의 차이점이 있습니다. 예를 들어, +EditText 요소에는 text 속성이 있으며 이는 EditText.setText()에 상응합니다.

        팁: 여러 가지 레이아웃 유형에 대해서는 보편적인 -레이아웃 객체를 참조하십시오. 여러 가지 레이아웃을 구축하는 데 대한 튜토리얼 모음도 있습니다. +레이아웃 객체를 참조하십시오. 여러 가지 레이아웃을 구축하는 데 대한 튜토리얼 모음도 있습니다. Hello 보기 튜토리얼 가이드를 참조하십시오.

        XML 쓰기

        @@ -100,20 +100,20 @@ EditText 요소에는 text 속성이 있으며 이는 </LinearLayout> -

        레이아웃을 XML로 선언하고 나면 그 파일을 Android 프로젝트의 res/layout/ 디렉터리 내에 +

        레이아웃을 XML로 선언하고 나면 그 파일을 Android 프로젝트의 res/layout/ 디렉터리 내에 .xml 확장자로 저장하여 적절하게 컴파일링되도록 합니다.

        레이아웃 XML 파일의 구문에 대한 자세한 정보는 레이아웃 리소스 문서에서 확인할 수 있습니다.

        XML 리소스 로딩

        -

        애플리케이션을 컴파일링하는 경우, 각 XML 레이아웃 파일이 -{@link android.view.View} 리소스 안에 컴파일링됩니다. 애플리케이션 코드로부터 가져온 레이아웃 리소스는 -{@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()} 콜백 +

        애플리케이션을 컴파일링하는 경우, 각 XML 레이아웃 파일이 +{@link android.view.View} 리소스 안에 컴파일링됩니다. 애플리케이션 코드로부터 가져온 레이아웃 리소스는 +{@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()} 콜백 구현에 로딩해야 합니다. -이렇게 하려면 {@link android.app.Activity#setContentView(int) setContentView()}를 호출한 다음, 이를 +이렇게 하려면 {@link android.app.Activity#setContentView(int) setContentView()}를 호출한 다음, 이를 R.layout.layout_file_name 형태로 레이아웃 리소스의 참조에 전달합니다. - 예를 들어, XML 레이아웃이 main_layout.xml로 저장된 경우, 이것을 액티비티에 대해 로딩하려면 + 예를 들어, XML 레이아웃이 main_layout.xml로 저장된 경우, 이것을 액티비티에 대해 로딩하려면 다음과 같이 하면 됩니다.

         public void onCreate(Bundle savedInstanceState) {
        @@ -122,8 +122,8 @@ public void onCreate(Bundle savedInstanceState) {
         }
         
        -

        액티비티 내의 onCreate() 콜백 메서드는 액티비티가 시작될 때 -Android 프레임워크가 호출합니다(수명 주기에 대한 논의는 +

        액티비티 내의 onCreate() 콜백 메서드는 액티비티가 시작될 때 +Android 프레임워크가 호출합니다(수명 주기에 대한 논의는 액티비티 문서에서 확인하십시오).

        @@ -134,24 +134,24 @@ Android 프레임워크가 호출합니다(수명 주기에 대한 논의는 몇몇 속성은 보기 객체에만 특화되어 있지만(예를 들어, TextView는 textSize 속성을 지원), 이와 같은 속성은 이 클래스를 확장할 수 있는 모든 보기 객체가 상속하기도 합니다. 모든 보기 객체에 공통으로 쓰이는 것도 몇 가지 있습니다. 왜냐하면 이들은 루트 보기 클래스에서 상속된 것이기 때문입니다(예: -id 속성). 그리고 나머지 속성은 "레이아웃 매개변수"로 간주됩니다. -이들은 보기 객체의 특정한 레이아웃 방향을 설명하는 것으로, 이는 해당 객체의 상위 VeiwGroup 객체에서 +id 속성). 그리고 나머지 속성은 "레이아웃 매개변수"로 간주됩니다. +이들은 보기 객체의 특정한 레이아웃 방향을 설명하는 것으로, 이는 해당 객체의 상위 VeiwGroup 객체에서 정의된 바에 따릅니다.

        ID

        모든 보기 객체에는 연관된 정수 ID가 있을 수 있습니다. 이는 트리 내에서 해당 보기를 고유하게 식별하기 위한 것입니다. -애플리케이션이 컴파일링되면 이 ID가 정수로 참조되지만, ID는 -일반적으로 레이아웃 XML 파일에 문자열로 할당되며, id 속성으로 쓰입니다. +애플리케이션이 컴파일링되면 이 ID가 정수로 참조되지만, ID는 +일반적으로 레이아웃 XML 파일에 문자열로 할당되며, id 속성으로 쓰입니다. 이것은 모든 보기 객체에 공통적인 XML 속성으로 ({@link android.view.View} 클래스가 정의) 이것을 매우 자주 사용하게 됩니다. ID에 대한, XML 태그 내에 있는 구문은 다음과 같습니다.

        android:id="@+id/my_button"
        -

        문자열 시작 부분에 있는 앳 기호(@)는 XML 파서가 ID 문자열의 나머지를 구문 분석하고 확장하여 -ID 리소스로 식별해야 한다는 것을 나타냅니다. 더하기 기호(+)는 이것이 새 리소스 이름이며, -이것을 반드시 생성하여 우리 리소스에 추가해야 한다는 것을 뜻합니다(R.java 파일에서). Android 프레임워크는 다른 ID 리소스도 아주 많이 -제공합니다. Android 리소스 ID를 참조할 때에는 더하기 기호는 필요하지 않지만 +

        문자열 시작 부분에 있는 앳 기호(@)는 XML 파서가 ID 문자열의 나머지를 구문 분석하고 확장하여 +ID 리소스로 식별해야 한다는 것을 나타냅니다. 더하기 기호(+)는 이것이 새 리소스 이름이며, +이것을 반드시 생성하여 우리 리소스에 추가해야 한다는 것을 뜻합니다(R.java 파일에서). Android 프레임워크는 다른 ID 리소스도 아주 많이 +제공합니다. Android 리소스 ID를 참조할 때에는 더하기 기호는 필요하지 않지만 android 패키지 네임스페이스를 다음과 같이 반드시 추가해야 합니다.

        android:id="@android:id/empty"

        android 패키지 네임스페이스를 제자리에 넣으면 이제 ID를 로컬 리소스 클래스에서가 아니라 android.R @@ -174,54 +174,54 @@ Button myButton = (Button) findViewById(R.id.my_button);

    -

    {@link android.widget.RelativeLayout}을 생성할 때에는 보기 객체의 ID를 정의하는 것이 중요합니다. -관계 레이아웃에서는 형제 보기가 또 다른 형제 보기와 관련된 자신의 레이아웃을 정의할 수 있으며, +

    {@link android.widget.RelativeLayout}을 생성할 때에는 보기 객체의 ID를 정의하는 것이 중요합니다. +관계 레이아웃에서는 형제 보기가 또 다른 형제 보기와 관련된 자신의 레이아웃을 정의할 수 있으며, 이를 고유한 ID로 참조하게 됩니다.

    -

    ID는 트리 전체를 통틀어 고유할 필요는 없지만, 트리에서 검색하고 있는 부분 내에서는 -고유해야 합니다(이것이 트리 전체인 경우가 잦으므로, 가급적이면 완전히 +

    ID는 트리 전체를 통틀어 고유할 필요는 없지만, 트리에서 검색하고 있는 부분 내에서는 +고유해야 합니다(이것이 트리 전체인 경우가 잦으므로, 가급적이면 완전히 고유한 것을 쓰는 것이 가장 좋습니다).

    레이아웃 매개변수

    -

    layout_something이라는 XML 레이아웃 속성이 +

    layout_something이라는 XML 레이아웃 속성이 보기가 상주하는 ViewGroup에 대해 적절한 보기의 레이아웃 매개변수를 정의합니다.

    모든 ViewGroup 클래스가 중첩된 클래스를 하나씩 구현하며 이것이 {@link -android.view.ViewGroup.LayoutParams}를 확장합니다. 이 하위 클래스에는 -각 하위 보기의 크기와 위치를 보기 그룹에 적절한 방식으로 정의하는 -속성 유형이 들어 있습니다. 그림 1에서 볼 수 있듯이, 상위 보기 그룹이 +android.view.ViewGroup.LayoutParams}를 확장합니다. 이 하위 클래스에는 +각 하위 보기의 크기와 위치를 보기 그룹에 적절한 방식으로 정의하는 +속성 유형이 들어 있습니다. 그림 1에서 볼 수 있듯이, 상위 보기 그룹이 각 하위 보기의 레이아웃 매개변수를 정의합니다(하위 보기 그룹 포함).

    -

    그림 1. 각 보기와 연관된 레이아웃 매개변수가 +

    그림 1. 각 보기와 연관된 레이아웃 매개변수가 있는 보기 계층을 시각화한 것입니다.

    -

    모든 LayoutParams 하위 클래스에는 설정 값에 대한 각기 자신만의 구문이 있다는 점을 -눈여겨 보십시오. 각 하위 요소는 자신의 상위에 적합한 LayoutParams를 정의해야 합니다. +

    모든 LayoutParams 하위 클래스에는 설정 값에 대한 각기 자신만의 구문이 있다는 점을 +눈여겨 보십시오. 각 하위 요소는 자신의 상위에 적합한 LayoutParams를 정의해야 합니다. 다만 이것은 자신의 하위에 대해 각기 다른 LayoutParams도 정의할 수 있습니다.

    -

    모든 보기 그룹에는 너비와 높이가 포함되며(layout_width 및 -layout_height), 각 보기는 이들을 반드시 정의해야 합니다. 선택 사항으로 +

    모든 보기 그룹에는 너비와 높이가 포함되며(layout_width 및 +layout_height), 각 보기는 이들을 반드시 정의해야 합니다. 선택 사항으로 여백과 테두리도 포함하는 LayoutParams도 많습니다.

    -

    너비와 높이는 정확한 치수로 지정할 수 있습니다. 다만 이것은 자주 하지 -않는 것이 좋습니다. 그보다는 다음과 같은 상수 중 하나를 사용하여 너비 또는 높이를 설정하는 경우가 +

    너비와 높이는 정확한 치수로 지정할 수 있습니다. 다만 이것은 자주 하지 +않는 것이 좋습니다. 그보다는 다음과 같은 상수 중 하나를 사용하여 너비 또는 높이를 설정하는 경우가 더 많습니다.

      -
    • wrap_content 보기에 콘텐츠에 필요한 치수대로 알아서 +
    • wrap_content 보기에 콘텐츠에 필요한 치수대로 알아서 크기를 조정하라고 합니다.
    • match_parent (다른 이름은 fill_parent 로, API 레벨 8 이전에 해당) 보기에 상위 보기 그룹이 허용하는 한 최대한으로 커지라고 합니다.
    -

    일반적으로 픽셀과 같이 절대적인 단위를 사용하여 레이아웃 너비와 높이를 지정하는 것은 -권장하지 않습니다. 그 대신, 밀도 독립적인 픽셀 단위와 같이 상대적인 측정치를 +

    일반적으로 픽셀과 같이 절대적인 단위를 사용하여 레이아웃 너비와 높이를 지정하는 것은 +권장하지 않습니다. 그 대신, 밀도 독립적인 픽셀 단위와 같이 상대적인 측정치를 사용하는 것(dp), wrap_content, 또는 -match_parent등이 더 낫습니다. 이렇게 하면 +match_parent등이 더 낫습니다. 이렇게 하면 애플리케이션이 다양한 기기 화면 크기에 걸쳐서도 적절하게 표시되도록 보장하는 데 도움이 되기 때문입니다. -허용된 측정 유형은 +허용된 측정 유형은 사용 가능한 리소스에 정의되어 있습니다.

    @@ -229,23 +229,23 @@ android.view.ViewGroup.LayoutParams}를 확장합니다. 이 하위 클래스에

    레이아웃 위치

    보기의 모양은 직사각형입니다. 보기에는 위치가 있으며, 이는 - 한 쌍의 왼쪽상단 좌표, 그리고 두 개의 치수가 너비와 높이를 나타내는 + 한 쌍의 왼쪽상단 좌표, 그리고 두 개의 치수가 너비와 높이를 나타내는 형식으로 표현됩니다. 위치와 치수의 단위는 픽셀입니다.

    - 보기의 위치를 검색할 수 있습니다. -{@link android.view.View#getLeft()} 및 {@link android.view.View#getTop()} 메서드를 호출하면 됩니다. 전자는 보기를 -나타내는 직사각형의 왼쪽, 즉 X 좌표를 반환합니다. 후자는 보기를 -나타내는 직사각형의 상단, 즉 Y 좌표를 반환합니다. 이들 메서드는 둘 다 -보기의 위치를 해당 보기의 상위와 관련지어 반환합니다. 예를 들어, -getLeft()가 20을 반환하는 경우 이는 해당 보기가 그 보기의 바로 상위의 왼쪽 가장자리에서 + 보기의 위치를 검색할 수 있습니다. +{@link android.view.View#getLeft()} 및 {@link android.view.View#getTop()} 메서드를 호출하면 됩니다. 전자는 보기를 +나타내는 직사각형의 왼쪽, 즉 X 좌표를 반환합니다. 후자는 보기를 +나타내는 직사각형의 상단, 즉 Y 좌표를 반환합니다. 이들 메서드는 둘 다 +보기의 위치를 해당 보기의 상위와 관련지어 반환합니다. 예를 들어, +getLeft()가 20을 반환하는 경우 이는 해당 보기가 그 보기의 바로 상위의 왼쪽 가장자리에서 오른쪽으로 20픽셀 떨어진 곳에 있다는 뜻입니다.

    - 이외에도 불필요한 계산을 피하기 위해 여러 가지 편의 메서드가 제공됩니다. + 이외에도 불필요한 계산을 피하기 위해 여러 가지 편의 메서드가 제공됩니다. 구체적으로 {@link android.view.View#getRight()} 및 {@link android.view.View#getBottom()}을 들 수 있습니다. 이들 메서드는 해당 보기를 나타내는 직사각형의 오른쪽과 하단 가장자리의 좌표를 반환합니다. 예를 들어 {@link android.view.View#getRight()}를 @@ -255,46 +255,46 @@ android.view.ViewGroup.LayoutParams}를 확장합니다. 이 하위 클래스에

    크기, 안쪽 여백 및 여백

    - 보기의 크기는 너비와 높이로 표현됩니다. 사실 하나의 보기는 + 보기의 크기는 너비와 높이로 표현됩니다. 사실 하나의 보기는 두 쌍의 너비 및 높이 값을 소유합니다.

    - 첫 번째 쌍을 측정된 너비 및 -측정된 높이라고 합니다. 이들 치수는 보기가 -상위 내에서 얼마나 커지고자 하는지를 정의합니다. 측정된 + 첫 번째 쌍을 측정된 너비 및 +측정된 높이라고 합니다. 이들 치수는 보기가 +상위 내에서 얼마나 커지고자 하는지를 정의합니다. 측정된 치수를 가져오려면 {@link android.view.View#getMeasuredWidth()} 및 {@link android.view.View#getMeasuredHeight()}를 호출하면 됩니다.

    - 두 번째 쌍은 단순히 너비높이라고 일컬으며, -때로는 그리기 너비그리기 높이로 부를 때도 있습니다. 이러한 -치수는 그리기 시간 및 레이아웃 후에 보기가 화면에 표시되는 실제 크기를 -정의합니다. 이들 값은 측정된 너비 및 높이와 달라도 되지만 -꼭 달라야 하는 것은 아닙니다. 너비와 높이를 가져오려면 + 두 번째 쌍은 단순히 너비높이라고 일컬으며, +때로는 그리기 너비그리기 높이로 부를 때도 있습니다. 이러한 +치수는 그리기 시간 및 레이아웃 후에 보기가 화면에 표시되는 실제 크기를 +정의합니다. 이들 값은 측정된 너비 및 높이와 달라도 되지만 +꼭 달라야 하는 것은 아닙니다. 너비와 높이를 가져오려면 {@link android.view.View#getWidth()} 및 {@link android.view.View#getHeight()}를 호출하면 됩니다.

    - 보기의 치수를 측정하려면 보기는 자신의 안쪽 여백을 감안합니다. 안쪽 여백은 + 보기의 치수를 측정하려면 보기는 자신의 안쪽 여백을 감안합니다. 안쪽 여백은 보기의 왼쪽, 상단, 오른쪽 및 하단 부분에 대해 픽셀로 표시됩니다. - 안쪽 여백은 정해진 픽셀 수를 사용하여 보기의 콘텐츠를 오프셋하는 데 쓰일 수도 -있습니다. 예를 들어 왼쪽 안쪽 여백을 2로 설정하면 해당 보기의 콘텐츠를 왼쪽 가장자리에서 -오른쪽으로 2픽셀 밀어냅니다. 안쪽 여백을 설정할 때에는 -{@link android.view.View#setPadding(int, int, int, int)} 메서드를 사용하면 되고, 이를 쿼리하려면 -{@link android.view.View#getPaddingLeft()}, {@link android.view.View#getPaddingTop()}, + 안쪽 여백은 정해진 픽셀 수를 사용하여 보기의 콘텐츠를 오프셋하는 데 쓰일 수도 +있습니다. 예를 들어 왼쪽 안쪽 여백을 2로 설정하면 해당 보기의 콘텐츠를 왼쪽 가장자리에서 +오른쪽으로 2픽셀 밀어냅니다. 안쪽 여백을 설정할 때에는 +{@link android.view.View#setPadding(int, int, int, int)} 메서드를 사용하면 되고, 이를 쿼리하려면 +{@link android.view.View#getPaddingLeft()}, {@link android.view.View#getPaddingTop()}, {@link android.view.View#getPaddingRight()} 및 {@link android.view.View#getPaddingBottom()}을 사용하면 됩니다.

    - 보기가 안쪽 여백을 정의할 수는 있지만, 여백에 대한 지원은 전혀 제공하지 -않습니다. 다만 보기 그룹이 그와 같은 지원을 제공합니다. 자세한 정보는 -{@link android.view.ViewGroup} 및 + 보기가 안쪽 여백을 정의할 수는 있지만, 여백에 대한 지원은 전혀 제공하지 +않습니다. 다만 보기 그룹이 그와 같은 지원을 제공합니다. 자세한 정보는 +{@link android.view.ViewGroup} 및 {@link android.view.ViewGroup.MarginLayoutParams}를 참조하십시오.

    -

    치수에 대한 자세한 정보는 +

    치수에 대한 자세한 정보는 치수 값을 참조하십시오.

    @@ -320,13 +320,13 @@ div.layout.first {

    보편적인 레이아웃

    -

    {@link android.view.ViewGroup} 클래스의 각 하위 클래스는 각기 고유한 방식으로 자신 안에 -중첩한 보기를 표시합니다. 아래는 Android 플랫폼에서 기본 제공되는, 보다 보편적인 레이아웃 유형을 +

    {@link android.view.ViewGroup} 클래스의 각 하위 클래스는 각기 고유한 방식으로 자신 안에 +중첩한 보기를 표시합니다. 아래는 Android 플랫폼에서 기본 제공되는, 보다 보편적인 레이아웃 유형을 몇 가지 나타낸 것입니다.

    -

    참고: 하나 이상의 레이아웃을 또 다른 레이아웃에 중첩하여 -UI 디자인을 이룰 수도 있지만, 레이아웃 계층을 가능한 한 얕게 유지하도록 -애써야 합니다. 중첩된 레이아웃이 적을수록 레이아웃이 더욱 빠르게 그려집니다(가로로 넓은 보기 계층이 +

    참고: 하나 이상의 레이아웃을 또 다른 레이아웃에 중첩하여 +UI 디자인을 이룰 수도 있지만, 레이아웃 계층을 가능한 한 얕게 유지하도록 +애써야 합니다. 중첩된 레이아웃이 적을수록 레이아웃이 더욱 빠르게 그려집니다(가로로 넓은 보기 계층이 깊은 보기 계층보다 낫습니다).

    알림 우선 순위

    - 원한다면, 알림에 우선 순위를 설정할 수 있습니다. 우선 순위는 + 원한다면, 알림에 우선 순위를 설정할 수 있습니다. 우선 순위는 기기 UI에 알림 표시 방식을 암시하는 역할을 합니다. 알림 우선 순위를 설정하려면, {@link android.support.v4.app.NotificationCompat.Builder#setPriority(int) NotificationCompat.Builder.setPriority()}를 호출하고 {@link -android.support.v4.app.NotificationCompat} 우선 순위 상수 중 하나에 전달합니다. +android.support.v4.app.NotificationCompat} 우선 순위 상수 중 하나에 전달합니다. 우선 순위 수준은 {@link android.support.v4.app.NotificationCompat#PRIORITY_MIN}(-2)에서 {@link android.support.v4.app.NotificationCompat#PRIORITY_MAX}(2)까지 다섯 개가 있습니다. 별도의 설정이 없을 경우, @@ -185,10 +185,10 @@ android.support.v4.app.NotificationCompat#PRIORITY_DEFAULT}(0)으로 설정됩

    단순 알림 만들기

    - 다음 조각은 사용자가 알림을 클릭하면 알리는 + 다음 조각은 사용자가 알림을 클릭하면 알리는 액티비티를 지정하는 단순한 알림을 나타냅니다. 이 코드는 -{@link android.support.v4.app.TaskStackBuilder} 객체를 생성하고 이를 사용하여 -해당 작업의 {@link android.app.PendingIntent}를 생성합니다. 이 패턴은 +{@link android.support.v4.app.TaskStackBuilder} 객체를 생성하고 이를 사용하여 +해당 작업의 {@link android.app.PendingIntent}를 생성합니다. 이 패턴은 액티비티를 시작할 때 탐색 보존 섹션에서 자세히 설명합니다.

    @@ -225,13 +225,13 @@ mNotificationManager.notify(mId, mBuilder.build());

    알림에 확장 레이아웃 적용

    - 확장된 보기에 알림을 나타나게 하려면, + 확장된 보기에 알림을 나타나게 하려면, 먼저 원하는 일반 보기 옵션으로 {@link android.support.v4.app.NotificationCompat.Builder} 객체를 생성합니다. 다음에는 확장된 레이아웃 객체의 인수로 {@link android.support.v4.app.NotificationCompat.Builder#setStyle Builder.setStyle()}을 호출합니다.

    - 확장 알림은 Android 4.1 이전 플랫폼에서 사용할 수 없다는 것을 명심하십시오. + 확장 알림은 Android 4.1 이전 플랫폼에서 사용할 수 없다는 것을 명심하십시오. Android 4.1 이하 플랫폼에서 알림을 처리하는 방법은 처리 호환성 섹션을 참조하십시오.

    @@ -264,7 +264,7 @@ mBuilder.setStyle(inBoxStyle);

    처리 호환성

    - + 알림 기능을 설정하는 메서드가 지원 라이브러리 클래스 {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder}에 있더라도 모든 알림 기능을 특정 버전에서 사용할 수 있는 것은 아닙니다. 예를 들어, 확장 알림에 따라 달라지는 작업 버튼은 Android @@ -294,13 +294,13 @@ NotificationCompat.Builder}를 이용해서 알림을 생성합니다. 또한, 사용자가 알림을 클릭하면 알림을 시작시키는 방식으로 모든 사용자에게 {@link android.app.Activity}에서 알림 기능을 사용할 수 있게 합니다. 이를 위해, -{@link android.app.Activity}를 위한 {@link android.app.PendingIntent}를 생성합니다. +{@link android.app.Activity}를 위한 {@link android.app.PendingIntent}를 생성합니다. {@link android.support.v4.app.NotificationCompat.Builder#setContentIntent setContentIntent()}를 호출하여 알림에 {@link android.app.PendingIntent}를 추가합니다.

  • 이제 알림에서 사용하고자 하는 확장 알림 기능을 추가합니다. 또한, 사용자가 알림을 클릭하면 시작되는 -{@link android.app.Activity}에서 개발자가 추가한 모든 기능을 +{@link android.app.Activity}에서 개발자가 추가한 모든 기능을 사용할 수 있어야 합니다.
  • @@ -310,18 +310,18 @@ setContentIntent()}를 호출하여 알림에 {@link android.app.PendingIntent}

    알림 관리

    - 같은 유형의 이벤트에서 알림을 여러 번 발행해야 할 경우, + 같은 유형의 이벤트에서 알림을 여러 번 발행해야 할 경우, 완전히 새로운 알림을 만드는 것은 삼가야 합니다. 대신, 일부 값을 변경하거나 추가하거나, 두 가지 조치를 모두 취하여 이전 알림을 업데이트하는 것이 좋습니다.

    예를 들어, Gmail은 읽지 않은 메시지 개수를 올리고 각 이메일의 요약을 알림에 추가하여 -새 이메일 도착을 알립니다. 이것을 일명 -알림을 "쌓는다"고 하며, 이는 +새 이메일 도착을 알립니다. 이것을 일명 +알림을 "쌓는다"고 하며, 이는 알림 디자인 가이드에 자세히 설명되어 있습니다.

    - 참고: 이 Gmail 기능에는 "받은편지함" 확장 레이아웃이 필요한데, + 참고: 이 Gmail 기능에는 "받은편지함" 확장 레이아웃이 필요한데, 이것은 Android 4.1부터 이용할 수 있는 확장 알림 기능의 일부입니다.

    @@ -331,16 +331,16 @@ setContentIntent()}를 호출하여 알림에 {@link android.app.PendingIntent}

    알림이 업데이트되도록 설정하려면, {@link android.app.NotificationManager#notify(int, android.app.Notification) NotificationManager.notify()}를 호출하여 알림 ID와 함께 발행합니다. - 알림을 발행한 후에 업데이트하려면, -{@link android.support.v4.app.NotificationCompat.Builder} 객체를 업데이트하거나 생성하고, -{@link android.app.Notification} 객체를 구축하고, -이전에 사용한 것과 같은 ID로 {@link android.app.Notification}을 발행합니다. 이전 알림이 + 알림을 발행한 후에 업데이트하려면, +{@link android.support.v4.app.NotificationCompat.Builder} 객체를 업데이트하거나 생성하고, +{@link android.app.Notification} 객체를 구축하고, +이전에 사용한 것과 같은 ID로 {@link android.app.Notification}을 발행합니다. 이전 알림이 여전히 표시되는 경우, 시스템은 -{@link android.app.Notification} 객체의 콘텐츠에서 알림을 업데이트합니다. 이전 알림을 무시할 경우, +{@link android.app.Notification} 객체의 콘텐츠에서 알림을 업데이트합니다. 이전 알림을 무시할 경우, 대신 새로운 알림이 생성됩니다.

    - 다음 코드 조각은 발생한 이벤트 개수를 반영하여 + 다음 코드 조각은 발생한 이벤트 개수를 반영하여 업데이트된 알림을 나타낸 것입니다. 이것은 알림을 쌓아 요약을 표시합니다.

    @@ -385,7 +385,7 @@ numMessages = 0;
     이 메서드도 현재 진행 중인 알림을 삭제합니다.
         
         
  • - {@link android.app.NotificationManager#cancelAll() cancelAll()}을 호출합니다. + {@link android.app.NotificationManager#cancelAll() cancelAll()}을 호출합니다. 이것은 이전에 발행한 알림을 모두 제거합니다.
  • @@ -393,9 +393,9 @@ numMessages = 0;

    액티비티를 시작할 때 탐색 보존

    - 알림에서 {@link android.app.Activity}를 시작할 때는 사용자의 예상 탐색 경험을 -보존해야 합니다. '뒤로'를 클릭하면 사용자를 애플리케이션의 정상 작업 흐름을 거쳐 메인 스크린으로 보내고, - '최근'을 클릭하면 + 알림에서 {@link android.app.Activity}를 시작할 때는 사용자의 예상 탐색 경험을 +보존해야 합니다. '뒤로'를 클릭하면 사용자를 애플리케이션의 정상 작업 흐름을 거쳐 메인 스크린으로 보내고, + '최근'을 클릭하면 {@link android.app.Activity}를 별개의 작업으로 표시합니다. 탐색 경험을 보존하려면 새 작업에서 {@link android.app.Activity}를 시작해야 합니다. 새로운 작업을 부여하기 위한 {@link android.app.PendingIntent} 설정 방법은 시작하는 @@ -406,19 +406,19 @@ numMessages = 0; 정규 액티비티

    - 애플리케이션의 정상적 작업 흐름의 일부인 {@link android.app.Activity}를 + 애플리케이션의 정상적 작업 흐름의 일부인 {@link android.app.Activity}를 시작합니다. 이 상황에서 {@link android.app.PendingIntent}를 설정하여 새 작업을 시작하고 애플리케이션의 정상적인 '뒤로' 동작을 재현하는 백 스택으로 {@link android.app.PendingIntent}를 제공합니다.

    - Gmail 앱에서 보낸 알림이 이것을 잘 보여줍니다. 하나의 이메일 메시지에 대한 -알림을 클릭하면 메시지 자체를 보게 됩니다. 뒤로를 터치하면 + Gmail 앱에서 보낸 알림이 이것을 잘 보여줍니다. 하나의 이메일 메시지에 대한 +알림을 클릭하면 메시지 자체를 보게 됩니다. 뒤로를 터치하면 알림에서 들어간 것이 아니라 메인 스크린에서 Gmail에 들어간 것처럼 Gmail을 통해 메인 스크린으로 돌아갑니다.

    - 이것은 알림을 터치하기만 하면 어느 애플리케이션에 있든 관계 없이 발생하는 -일입니다. 예를 들어, Gmail에서 메시지를 작성하다가 + 이것은 알림을 터치하기만 하면 어느 애플리케이션에 있든 관계 없이 발생하는 +일입니다. 예를 들어, Gmail에서 메시지를 작성하다가 한 이메일에 대한 알림을 클릭하면 해당 이메일로 바로 이동합니다. 뒤로 를 터치하면 작성 중인 메시지가 아니라 받은편지함과 메인 스크린으로 돌아갑니다. @@ -429,18 +429,18 @@ Gmail에 들어간 것처럼 Gmail을 통해 메인 스크린으로 돌아갑니

    {@link android.app.Activity}가 알림에서 시작될 경우 사용자에게는 이것만 보입니다. - {@link android.app.Activity}는 알림 자체에서 표시하기 어려운 정보를 제공하므로 -어떤 면에서는 알림을 확장하는 셈입니다. 이 상황에서는, -{@link android.app.PendingIntent}를 설정하고 새로운 작업에서 시작합니다. -시작된 {@link android.app.Activity}는 -애플리케이션 액티비티 흐름의 일부가 아니므로 백 스택을 생성하지 않아도 됩니다. 뒤로를 클릭하면 사용자는 여전히 + {@link android.app.Activity}는 알림 자체에서 표시하기 어려운 정보를 제공하므로 +어떤 면에서는 알림을 확장하는 셈입니다. 이 상황에서는, +{@link android.app.PendingIntent}를 설정하고 새로운 작업에서 시작합니다. +시작된 {@link android.app.Activity}는 +애플리케이션 액티비티 흐름의 일부가 아니므로 백 스택을 생성하지 않아도 됩니다. 뒤로를 클릭하면 사용자는 여전히 메인 스크린으로 돌아갑니다.

    정규 액티비티 PendingIntent 설정

    - 직접 진입 + 직접 진입 {@link android.app.Activity}를 시작하는 {@link android.app.PendingIntent}를 설정하려면 다음과 같은 단계를 따르십시오.

      @@ -448,7 +448,7 @@ Gmail에 들어간 것처럼 Gmail을 통해 메인 스크린으로 돌아갑니 매니페스트에서 애플리케이션의 {@link android.app.Activity} 계층을 정의합니다.
      1. - Android 4.0.3 이전에 대한 지원을 추가합니다. 이렇게 하려면 + Android 4.0.3 이전에 대한 지원을 추가합니다. 이렇게 하려면 <meta-data> 요소를 @@ -506,39 +506,39 @@ Gmail에 들어간 것처럼 Gmail을 통해 메인 스크린으로 돌아갑니 TaskStackBuilder.create()}를 호출하여 스택 빌더를 생성합니다.
      2. - + {@link android.support.v4.app.TaskStackBuilder#addParentStack addParentStack()}을 호출하여 스택 빌더를 백 스택에 추가합니다. 매니페스트에서 정의한 계층의 각 {@link android.app.Activity}의 경우, 백 스택에 -{@link android.app.Activity}를 시작하는 {@link android.content.Intent} 객체가 포함됩니다. 이 메서드는 새로운 작업에서 +{@link android.app.Activity}를 시작하는 {@link android.content.Intent} 객체가 포함됩니다. 이 메서드는 새로운 작업에서 스택을 시작하는 플래그도 추가합니다.

        - 참고: + 참고: {@link android.support.v4.app.TaskStackBuilder#addParentStack addParentStack()}에 대한 인수가 -시작된 {@link android.app.Activity}의 참조이기는 하지만, 이 메서드 호출은 +시작된 {@link android.app.Activity}의 참조이기는 하지만, 이 메서드 호출은 {@link android.app.Activity}를 시작하는 {@link android.content.Intent}를 추가하지 않습니다. 대신, 그 부분은 다음 단계에서 해결합니다.

      3. - -{@link android.support.v4.app.TaskStackBuilder#addNextIntent addNextIntent()}를 호출하여 {@link android.app.Activity}를 시작하는 {@link android.content.Intent}를 + +{@link android.support.v4.app.TaskStackBuilder#addNextIntent addNextIntent()}를 호출하여 {@link android.app.Activity}를 시작하는 {@link android.content.Intent}를 추가합니다. 첫 번째 단계에서 생성한 {@link android.content.Intent}를 {@link android.support.v4.app.TaskStackBuilder#addNextIntent addNextIntent()}에 대한 인수로 전달합니다.
      4. - 필요할 경우 + 필요할 경우 {@link android.support.v4.app.TaskStackBuilder#editIntentAt TaskStackBuilder.editIntentAt()}을 호출하여 스택에서{@link android.content.Intent} 객체에 대한 인수를 추가합니다. 이것은 사용자가 '뒤로'를 사용하여 탐색할 때 대상{@link android.app.Activity}가 의미 있는 데이터를 표시하도록 보장하기 위해 때때로 필요한 절차입니다.
      5. - 이 백 스택에 대한 {@link android.app.PendingIntent}를 가져옵니다. 이때 + 이 백 스택에 대한 {@link android.app.PendingIntent}를 가져옵니다. 이때 {@link android.support.v4.app.TaskStackBuilder#getPendingIntent getPendingIntent()}를 호출하는 방법을 씁니다. - 그러면 이 {@link android.app.PendingIntent}를 + 그러면 이 {@link android.app.PendingIntent}를 {@link android.support.v4.app.NotificationCompat.Builder#setContentIntent setContentIntent()}에 대한 인수로 사용할 수 있습니다.
      6. @@ -569,21 +569,21 @@ mNotificationManager.notify(id, builder.build());

        특수 액티비티 PendingIntent 설정

        - 다음 섹션에서는 특수 액티비티 + 다음 섹션에서는 특수 액티비티 {@link android.app.PendingIntent}를 설정하는 법을 설명합니다.

        - 특수 {@link android.app.Activity}에는 백 스택이 필요하지 않습니다. 따라서 매니페스트에서 이것의 -{@link android.app.Activity} 계층을 정의하지 않아도 되고, -백 스택을 구축하기 위해 -{@link android.support.v4.app.TaskStackBuilder#addParentStack addParentStack()}을 -호출하지 않아도 됩니다. 대신 매니페스트를 사용하여 {@link android.app.Activity} 작업 옵션을 설정하고, -{@link android.app.PendingIntent}를 생성하십시오. 이때 + 특수 {@link android.app.Activity}에는 백 스택이 필요하지 않습니다. 따라서 매니페스트에서 이것의 +{@link android.app.Activity} 계층을 정의하지 않아도 되고, +백 스택을 구축하기 위해 +{@link android.support.v4.app.TaskStackBuilder#addParentStack addParentStack()}을 +호출하지 않아도 됩니다. 대신 매니페스트를 사용하여 {@link android.app.Activity} 작업 옵션을 설정하고, +{@link android.app.PendingIntent}를 생성하십시오. 이때 {@link android.app.PendingIntent#getActivity getActivity()}를 호출하는 방법을 씁니다.

        1. - 매니페스트에서 다음 속성을 {@link android.app.Activity}에 대한 + 매니페스트에서 다음 속성을 {@link android.app.Activity}에 대한 <activity> 요소에 추가합니다.
          @@ -597,10 +597,10 @@ mNotificationManager.notify(id, builder.build()); android:taskAffinity=""
          - 이것은 개발자가 코드에서 설정하는 -{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_NEW_TASK} 플래그와 더불어 -이 {@link android.app.Activity}가 -애플리케이션의 기본 작업으로 들어가지 않게 보장합니다. 애플리케이션의 기본 유사성을 + 이것은 개발자가 코드에서 설정하는 +{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_NEW_TASK} 플래그와 더불어 +이 {@link android.app.Activity}가 +애플리케이션의 기본 작업으로 들어가지 않게 보장합니다. 애플리케이션의 기본 유사성을 가지고 있는 기존 작업은 모두 영향을 받지 않습니다.
          @@ -629,23 +629,23 @@ mNotificationManager.notify(id, builder.build()); 알림을 구축 및 발행합니다.
          1. - + {@link android.app.Activity}를 시작하는 {@link android.content.Intent}를 생성합니다.
          2. - {@link android.app.Activity}가 새로운, 빈 작업에서 시작되도록 설정합니다. 이때 -{@link android.content.Intent#setFlags setFlags()}를 + {@link android.app.Activity}가 새로운, 빈 작업에서 시작되도록 설정합니다. 이때 +{@link android.content.Intent#setFlags setFlags()}를 {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_NEW_TASK} - 및 + 및 {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TASK FLAG_ACTIVITY_CLEAR_TASK} 플래그와 함께 호출하면 됩니다.
          3. {@link android.content.Intent}에 필요한 다른 모든 옵션을 설정합니다.
          4. - {@link android.app.PendingIntent}를 {@link android.content.Intent}로부터 + {@link android.app.PendingIntent}를 {@link android.content.Intent}로부터 생성합니다. 이때 {@link android.app.PendingIntent#getActivity getActivity()}를 호출하면 됩니다. - 그러면 이 {@link android.app.PendingIntent}를 + 그러면 이 {@link android.app.PendingIntent}를 {@link android.support.v4.app.NotificationCompat.Builder#setContentIntent setContentIntent()}에 대한 인수로 사용할 수 있습니다.
          5. @@ -687,24 +687,24 @@ mNotificationManager.notify(id, builder.build());

            알림에서 진행 상태 표시

            - 알림에는 사용자에게 진행 중인 작업의 상태를 보여주는 -애니메이션 진행 표시기를 포함할 수 있습니다. 작업이 얼마나 걸릴지, 주어진 시점에 어느 정도 완료되었는지를 추정할 수 있는 경우 -표시기의 "확정적" 형태(진행률 표시줄)를 -사용하십시오. 작업의 길이를 추정할 수 없으면, 표시기의 + 알림에는 사용자에게 진행 중인 작업의 상태를 보여주는 +애니메이션 진행 표시기를 포함할 수 있습니다. 작업이 얼마나 걸릴지, 주어진 시점에 어느 정도 완료되었는지를 추정할 수 있는 경우 +표시기의 "확정적" 형태(진행률 표시줄)를 +사용하십시오. 작업의 길이를 추정할 수 없으면, 표시기의 "비확정적" 형태(액티비티 표시기)를 사용하십시오.

            - 진행 상태 표시기는 + 진행 상태 표시기는 {@link android.widget.ProgressBar} 클래스의 플랫폼 구현으로 표시됩니다.

            - Android 4.0부터 시작되는 플랫폼에서 진행 상태 표시기를 사용하려면, -{@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress()}를 호출하십시오. 이전 -버전의 경우, 개발자 나름의 사용자 지정 알림 레이아웃을 생성해야 하며 여기에 + Android 4.0부터 시작되는 플랫폼에서 진행 상태 표시기를 사용하려면, +{@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress()}를 호출하십시오. 이전 +버전의 경우, 개발자 나름의 사용자 지정 알림 레이아웃을 생성해야 하며 여기에 {@link android.widget.ProgressBar} 보기가 포함되어 있어야 합니다.

            - 다음 섹션은 + 다음 섹션은 {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress()}를 사용하여 알림의 진행 상태를 표시하는 법을 설명합니다.

            @@ -712,15 +712,15 @@ mNotificationManager.notify(id, builder.build());

            확정적인 진행률 표시줄을 표시하려면 {@link android.support.v4.app.NotificationCompat.Builder#setProgress -setProgress(max, progress, false)}를 호출하여 표시줄을 알림에 추가하고, 그 다음에 알림을 발행합니다. 작업이 진행되는 동안 -progress를 증가시키고 알림을 업데이트합니다. 작업이 끝날 무렵 -progressmax와 같아야 합니다. +setProgress(max, progress, false)}를 호출하여 표시줄을 알림에 추가하고, 그 다음에 알림을 발행합니다. 작업이 진행되는 동안 +progress를 증가시키고 알림을 업데이트합니다. 작업이 끝날 무렵 +progressmax와 같아야 합니다. {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress()}를 호출하는 보편적인 방법은 max를 100에 설정하고 작업에 대한 "완료 비율" 값에 따라 progress를 증가시키는 것입니다.

            - 작업이 완료되면 진행률 표시줄이 표시되는 상태로 둘 수도 있고, 제거할 수도 있습니다. 어느 경우를 택하더라도 + 작업이 완료되면 진행률 표시줄이 표시되는 상태로 둘 수도 있고, 제거할 수도 있습니다. 어느 경우를 택하더라도 알림 텍스트를 업데이트하여 작업이 완료되었다고 표시하는 것을 잊지 마십시오. 진행률 표시줄을 제거하려면, {@link android.support.v4.app.NotificationCompat.Builder#setProgress @@ -773,15 +773,15 @@ new Thread(

            비확정적 액티비티 표시기를 표시하려면, {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress(0, 0, true)}으로 알림에 표시기를 추가하고(처음의 인수 두 개는 무시합니다) -, 알림을 발행합니다. 그 결과로 +, 알림을 발행합니다. 그 결과로 진행률 표시줄과 같은 스타일의 표시기가 나타납니다. 다만 이것은 애니메이션이 계속 진행 중입니다.

            - 작업을 시작할 때 알림을 발행합니다. 애니메이션은 -알림을 수정할 때까지 실행됩니다. 작업이 완료되면, + 작업을 시작할 때 알림을 발행합니다. 애니메이션은 +알림을 수정할 때까지 실행됩니다. 작업이 완료되면, {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress(0, 0, false)}를 호출하고 알림을 업데이트하여 액티비티 표시기를 제거합니다. - 이 작업은 항상 해야 합니다. 하지 않으면, 작업이 완료되더라도 애니메이션이 계속 실행됩니다. 또한, + 이 작업은 항상 해야 합니다. 하지 않으면, 작업이 완료되더라도 애니메이션이 계속 실행됩니다. 또한, 알림 텍스트를 변경하여 작업이 완료되었음을 나타내는 것을 잊지 마십시오.

            @@ -806,19 +806,19 @@ mNotifyManager.notify(0, mBuilder.build());

            알림 메타데이터

            -

            알림은 +

            알림은 다음 {@link android.support.v4.app.NotificationCompat.Builder} 메서드로 할당된 메타데이터에 따라 정렬할 수 있습니다.

              -
            • {@link android.support.v4.app.NotificationCompat.Builder#setCategory(java.lang.String) setCategory()}는 +
            • {@link android.support.v4.app.NotificationCompat.Builder#setCategory(java.lang.String) setCategory()}는 기기가 우선 순위 모드일 때 앱 알림을 처리하는 방법을 시스템에 전달합니다 (예를 들어, 알림이 수신 전화나 채팅 메시지, 알람 등을 나타낼 경우).
            • -
            • {@link android.support.v4.app.NotificationCompat.Builder#setPriority(int) setPriority()}는 -우선 순위 필드가 포함된 알림을 {@code PRIORITY_MAX} 또는 {@code PRIORITY_HIGH}로 설정하고, +
            • {@link android.support.v4.app.NotificationCompat.Builder#setPriority(int) setPriority()}는 +우선 순위 필드가 포함된 알림을 {@code PRIORITY_MAX} 또는 {@code PRIORITY_HIGH}로 설정하고, 알림에 소리나 진동이 포함되어 있을 경우 작은 부동 창에 나타나게 합니다.
            • -
            • {@link android.support.v4.app.NotificationCompat.Builder#addPerson(java.lang.String) addPerson()}을 -사용하면 알림에 사람 목록을 추가할 수 있게 해줍니다. 개발자의 앱은 이 신호를 사용하여 -시스템에 지정된 사람들로부터 받은 알림을 함께 그룹화해야 한다고 알리거나, 이런 사람들로부터 받은 알림을 +
            • {@link android.support.v4.app.NotificationCompat.Builder#addPerson(java.lang.String) addPerson()}을 +사용하면 알림에 사람 목록을 추가할 수 있게 해줍니다. 개발자의 앱은 이 신호를 사용하여 +시스템에 지정된 사람들로부터 받은 알림을 함께 그룹화해야 한다고 알리거나, 이런 사람들로부터 받은 알림을 더욱 중요한 것으로 순위를 높일 수 있습니다.
            @@ -832,10 +832,10 @@ mNotifyManager.notify(0, mBuilder.build());

            헤드업 알림

            Android 5.0(API 레벨 21)에서는 알림을 작은 부동 창에 나타낼 수 있습니다 -(다른 말로 헤드업 알림이라고 부릅니다). 이것은 기기가 활성 상태일 때(즉, -기기가 잠금 해제 상태이며 화면에 켜져 있는 경우) 해당됩니다. 이와 같은 알림은 -외견상 일반적인 알림의 소형 형태와 비슷해 보이지만, -해드업 알림에서는 작업 버튼도 표시한다는 점이 다릅니다. 사용자는 현재 앱을 떠나지 않고도 +(다른 말로 헤드업 알림이라고 부릅니다). 이것은 기기가 활성 상태일 때(즉, +기기가 잠금 해제 상태이며 화면에 켜져 있는 경우) 해당됩니다. 이와 같은 알림은 +외견상 일반적인 알림의 소형 형태와 비슷해 보이지만, +해드업 알림에서는 작업 버튼도 표시한다는 점이 다릅니다. 사용자는 현재 앱을 떠나지 않고도 헤드업 알림에 조치를 취하거나 이를 무시할 수 있습니다.

            헤드업 알림을 트리거할 수 있는 조건의 예시를 몇 가지 소개하면 다음과 같습니다.

            @@ -843,55 +843,55 @@ mNotifyManager.notify(0, mBuilder.build());
            • 사용자 액티비티가 전체 화면 모드이거나(앱이 {@link android.app.Notification#fullScreenIntent}를 사용할 경우)
            • -
            • 알림의 우선 순위가 높고 +
            • 알림의 우선 순위가 높고 벨소리나 진동을 사용할 경우

            잠금 화면 알림

            -

            Android 5.0 (API 레벨 21) 릴리스부터 알림이 잠금 화면에도 -나타날 수 있게 되었습니다. 앱은 이 기능을 사용하면 미디어 재생 제어와 다른 보편적인 작업을 -제공할 수 있습니다. 사용자는 설정을 통해 잠금 화면에 알림 표시 여부를 선택할 수 있고, +

            Android 5.0 (API 레벨 21) 릴리스부터 알림이 잠금 화면에도 +나타날 수 있게 되었습니다. 앱은 이 기능을 사용하면 미디어 재생 제어와 다른 보편적인 작업을 +제공할 수 있습니다. 사용자는 설정을 통해 잠금 화면에 알림 표시 여부를 선택할 수 있고, 개발자는 앱의 알림이 잠금 화면에 표시될지 여부를 지정할 수 있습니다.

            가시성 설정

            -

            보안 잠금 화면에 알림이 얼마나 상세하게 표시될 것인지 그 수준을 앱이 제어할 수 -있습니다. {@link android.support.v4.app.NotificationCompat.Builder#setVisibility(int) setVisibility()}를 호출하고 +

            보안 잠금 화면에 알림이 얼마나 상세하게 표시될 것인지 그 수준을 앱이 제어할 수 +있습니다. {@link android.support.v4.app.NotificationCompat.Builder#setVisibility(int) setVisibility()}를 호출하고 다음 값 중 하나를 지정합니다.

              -
            • {@link android.support.v4.app.NotificationCompat#VISIBILITY_PUBLIC}은 +
            • {@link android.support.v4.app.NotificationCompat#VISIBILITY_PUBLIC}은 알림의 전체 콘텐츠를 표시합니다.
            • -
            • {@link android.support.v4.app.NotificationCompat#VISIBILITY_SECRET}은 +
            • {@link android.support.v4.app.NotificationCompat#VISIBILITY_SECRET}은 이 알림의 어떤 부분도 화면에 표시하지 않습니다.
            • -
            • {@link android.support.v4.app.NotificationCompat#VISIBILITY_PRIVATE}은 +
            • {@link android.support.v4.app.NotificationCompat#VISIBILITY_PRIVATE}은 알림 아이콘과 콘텐츠 제목 등의 기본 정보는 표시하지만 알림의 전체 콘텐츠는 숨깁니다.

            {@link android.support.v4.app.NotificationCompat#VISIBILITY_PRIVATE}으로 설정하면 , -알림 콘텐츠의 대체 버전을 제공할 수도 있습니다. 이렇게 하면 특정 세부 사항만 숨깁니다. 예를 들어, -SMS 앱에서 3개의 새 문자 메시지가 있습니다.라고 표시하면서도 -문자 메시지의 내용과 발신자는 숨길 수 있습니다. 이 대체 알림을 제공하려면, 우선 대체 알림을 생성합니다. 이때 -{@link android.support.v4.app.NotificationCompat.Builder}를 사용합니다. 비공개 알림 객체를 -생성하는 경우, 대체 알림을 이에 첨부할 때 +알림 콘텐츠의 대체 버전을 제공할 수도 있습니다. 이렇게 하면 특정 세부 사항만 숨깁니다. 예를 들어, +SMS 앱에서 3개의 새 문자 메시지가 있습니다.라고 표시하면서도 +문자 메시지의 내용과 발신자는 숨길 수 있습니다. 이 대체 알림을 제공하려면, 우선 대체 알림을 생성합니다. 이때 +{@link android.support.v4.app.NotificationCompat.Builder}를 사용합니다. 비공개 알림 객체를 +생성하는 경우, 대체 알림을 이에 첨부할 때 {@link android.support.v4.app.NotificationCompat.Builder#setPublicVersion(android.app.Notification) setPublicVersion()} 메서드를 통합니다.

            잠금 화면에서 미디어 재생 제어

            -

            Android 5.0(API 레벨 21)의 잠금 화면에서는 더 이상 -{@link android.media.RemoteControlClient}를 기반으로 한 미디어 제어를 표시하지 않습니다. 이는 사용되지 않고 있기 때문입니다. 대신, -{@link android.app.Notification.MediaStyle} 템플릿을 +

            Android 5.0(API 레벨 21)의 잠금 화면에서는 더 이상 +{@link android.media.RemoteControlClient}를 기반으로 한 미디어 제어를 표시하지 않습니다. 이는 사용되지 않고 있기 때문입니다. 대신, +{@link android.app.Notification.MediaStyle} 템플릿을 {@link android.app.Notification.Builder#addAction(android.app.Notification.Action) addAction()} 메서드와 함께 사용하십시오. 이 메서드는 작업을 클릭할 수 있는 아이콘으로 변환해줍니다.

            -

            참고: 이 템플릿과 {@link android.app.Notification.Builder#addAction(android.app.Notification.Action) addAction()} -메서드는 지원 라이브러리에 포함되어 있지 않으므로 이 기능은 Android 5.0 이상에서만 +

            참고: 이 템플릿과 {@link android.app.Notification.Builder#addAction(android.app.Notification.Action) addAction()} +메서드는 지원 라이브러리에 포함되어 있지 않으므로 이 기능은 Android 5.0 이상에서만 실행됩니다.

            -

            Android 5.0의 잠금 화면에서 미디어 재생 제어를 표시하려면, -위에 설명한 바와 같이 가시성을 {@link android.support.v4.app.NotificationCompat#VISIBILITY_PUBLIC}으로 설정합니다. 그런 다음 다음 샘플 코드에서 설명한 바와 같이 작업을 추가하고 +

            Android 5.0의 잠금 화면에서 미디어 재생 제어를 표시하려면, +위에 설명한 바와 같이 가시성을 {@link android.support.v4.app.NotificationCompat#VISIBILITY_PUBLIC}으로 설정합니다. 그런 다음 다음 샘플 코드에서 설명한 바와 같이 작업을 추가하고 {@link android.app.Notification.MediaStyle} 템플릿을 설정합니다.

            @@ -914,7 +914,7 @@ Notification notification = new Notification.Builder(context) .build();
    -

    참고: {@link android.media.RemoteControlClient}를 +

    참고: {@link android.media.RemoteControlClient}를 사용하지 않게 된 것은 미디어 제어에 이외에도 더 많은 영향을 미칩니다. 미디어 세션을 관리하고 재생을 제어하기 위한 새 API에 관한 자세한 정보는 미디어 재생 제어를 참조하십시오.

    @@ -923,57 +923,57 @@ Notification notification = new Notification.Builder(context)

    사용자 지정 알림 레이아웃

    - 알림 프레임워크를 사용하면 사용자 지정 레이아웃을 정의할 수 있습니다. + 알림 프레임워크를 사용하면 사용자 지정 레이아웃을 정의할 수 있습니다. 사용자 지정 레이아웃은 {@link android.widget.RemoteViews} 객체에서 알림의 외관을 정의합니다. 사용자 지정 레이아웃 알림은 일반적인 알림과 비슷하지만, 이들은 XML 레이아웃 파일에서 정의한 {@link android.widget.RemoteViews}에 기초합니다.

    - 사용자 지정 알림 레이아웃에 사용할 수 있는 높이는 알림 보기에 따라 다릅니다. 일반 + 사용자 지정 알림 레이아웃에 사용할 수 있는 높이는 알림 보기에 따라 다릅니다. 일반 보기 레이아웃은 64dp로 제한되어 있으며 확장 보기 레이아웃은 256dp로 제한되어 있습니다.

    - 사용자 지정 레이아웃을 정의하려면 -XML 레이아웃 파일을 팽창하는 {@link android.widget.RemoteViews} 객체를 인스턴트화하는 것부터 시작합니다. 그런 다음, + 사용자 지정 레이아웃을 정의하려면 +XML 레이아웃 파일을 팽창하는 {@link android.widget.RemoteViews} 객체를 인스턴트화하는 것부터 시작합니다. 그런 다음, -{@link android.support.v4.app.NotificationCompat.Builder#setContentTitle setContentTitle()}과 같은 메서드를 호출하는 대신 -{@link android.support.v4.app.NotificationCompat.Builder#setContent setContent()}를 호출합니다. 사용자 지정 알림에서 +{@link android.support.v4.app.NotificationCompat.Builder#setContentTitle setContentTitle()}과 같은 메서드를 호출하는 대신 +{@link android.support.v4.app.NotificationCompat.Builder#setContent setContent()}를 호출합니다. 사용자 지정 알림에서 콘텐츠 세부 정보를 설정하려면 {@link android.widget.RemoteViews}의 메서드를 사용하여 보기의 하위 요소에 대한 값을 설정합니다.

    1. - 알림에 대한 XML 레이아웃은 별도의 파일에 생성하십시오. 파일 이름은 원하는 대로 + 알림에 대한 XML 레이아웃은 별도의 파일에 생성하십시오. 파일 이름은 원하는 대로 아무 것이나 사용해도 좋지만, 확장자는 .xml을 사용해야 합니다.
    2. - 앱에서 {@link android.widget.RemoteViews} 메서드를 사용하여 알림의 아이콘과 텍스트를 -정의합니다. 이 {@link android.widget.RemoteViews} 객체를 -{@link android.support.v4.app.NotificationCompat.Builder} 안에 넣으십시오. -{@link android.support.v4.app.NotificationCompat.Builder#setContent setContent()}를 호출하면 됩니다. 배경 -{@link android.graphics.drawable.Drawable}을 + 앱에서 {@link android.widget.RemoteViews} 메서드를 사용하여 알림의 아이콘과 텍스트를 +정의합니다. 이 {@link android.widget.RemoteViews} 객체를 +{@link android.support.v4.app.NotificationCompat.Builder} 안에 넣으십시오. +{@link android.support.v4.app.NotificationCompat.Builder#setContent setContent()}를 호출하면 됩니다. 배경 +{@link android.graphics.drawable.Drawable}을 {@link android.widget.RemoteViews} 객체에서 설정하는 것은 삼가하십시오. 텍스트 색상을 읽을 수 없게 될 수도 있습니다.

    - {@link android.widget.RemoteViews} 클래스에도 개발자가 손쉽게 사용할 수 있는 여러 가지 메서드가 포함되어 있습니다. 이를 이용해 -{@link android.widget.Chronometer} 또는 {@link android.widget.ProgressBar}를 + {@link android.widget.RemoteViews} 클래스에도 개발자가 손쉽게 사용할 수 있는 여러 가지 메서드가 포함되어 있습니다. 이를 이용해 +{@link android.widget.Chronometer} 또는 {@link android.widget.ProgressBar}를 알림의 레이아웃에 추가하면 됩니다. 알림의 사용자 지정 레이아웃 생성에 관한 자세한 정보는 {@link android.widget.RemoteViews} 참조 문서를 참조하십시오.

    - 주의: 사용자 지정 레이아웃을 사용하는 경우, -사용자 지정 레이아웃이 다양한 기기 방향과 해상도에서 작동하는지 각별히 주의를 기울여 확인하십시오. 이 조언은 -모든 보기 레이아웃에 공통적으로 적용되지만, 특히 알림에 중요한 의미를 지닙니다. -알림 창에서는 공간이 굉장히 제한되어 있기 때문입니다. 사용자 지정 레이아웃을 너무 복잡하게 만들지 마시고, + 주의: 사용자 지정 레이아웃을 사용하는 경우, +사용자 지정 레이아웃이 다양한 기기 방향과 해상도에서 작동하는지 각별히 주의를 기울여 확인하십시오. 이 조언은 +모든 보기 레이아웃에 공통적으로 적용되지만, 특히 알림에 중요한 의미를 지닙니다. +알림 창에서는 공간이 굉장히 제한되어 있기 때문입니다. 사용자 지정 레이아웃을 너무 복잡하게 만들지 마시고, 여러 가지 구성에서 테스트하는 것을 잊지 마십시오.

    사용자 지정 알림 텍스트에 스타일 리소스 사용

    - 사용자 지정 알림의 텍스트에는 항상 스타일 리소스를 사용하십시오. 알림의 배경 색상은 기기와 버전별로 다를 수 있습니다. -스타일 리소스를 사용하면 이러한 차이를 -감안하는 데 도움이 됩니다. Android 2.3부터 시스템은 -표준 알림 레이아웃 텍스트의 스타일을 정의했습니다. Android 2.3 이상을 대상으로 하는 + 사용자 지정 알림의 텍스트에는 항상 스타일 리소스를 사용하십시오. 알림의 배경 색상은 기기와 버전별로 다를 수 있습니다. +스타일 리소스를 사용하면 이러한 차이를 +감안하는 데 도움이 됩니다. Android 2.3부터 시스템은 +표준 알림 레이아웃 텍스트의 스타일을 정의했습니다. Android 2.3 이상을 대상으로 하는 애플리케이션에서와 같은 스타일을 사용하면 텍스트가 디스플레이 배경에서도 잘 보이도록 할 수 있습니다.

    diff --git a/docs/html-intl/intl/ko/guide/topics/ui/overview.jd b/docs/html-intl/intl/ko/guide/topics/ui/overview.jd index eb288f1532aeb..72e5692e80e46 100644 --- a/docs/html-intl/intl/ko/guide/topics/ui/overview.jd +++ b/docs/html-intl/intl/ko/guide/topics/ui/overview.jd @@ -3,9 +3,9 @@ page.title=UI 개요

    Android 앱의 모든 사용자 인터페이스 요소는 {@link android.view.View}와 -{@link android.view.ViewGroup} 개체를 사용하여 구축합니다. {@link android.view.View}는 사용자가 상호 작용할 수 있는 무언가를 -화면에 그리는 객체입니다. {@link android.view.ViewGroup}은 -인터페이스 레이아웃을 정의하기 위해 다른 {@link android.view.View}(및{@link android.view.ViewGroup}) 객체를 +{@link android.view.ViewGroup} 개체를 사용하여 구축합니다. {@link android.view.View}는 사용자가 상호 작용할 수 있는 무언가를 +화면에 그리는 객체입니다. {@link android.view.ViewGroup}은 +인터페이스 레이아웃을 정의하기 위해 다른 {@link android.view.View}(및{@link android.view.ViewGroup}) 객체를 보유하는 객체입니다.

    Android는 공통 입력 제어(버튼 및 텍스트 필드)와 다양한 레이아웃 모델(선형 또는 관계 레이아웃)을 제공하는 {@link android.view.View}와 {@link @@ -16,30 +16,30 @@ android.view.ViewGroup} 하위 클래스의

    사용자 인터페이스 레이아웃

    앱의 각 구성 요소에 대한 사용자 인터페이스는 그림 1에서 나타난 바와 같이 {@link -android.view.View}와 {@link android.view.ViewGroup} 객체의 계층으로 정의됩니다. 각 보기 그룹은 -하위 보기를 체계화하는 투명한 컨테이너이고, -하위 보기는 UI의 일부분을 그리는 제어나 다른 위젯일 수 있습니다. -이 계층 트리는 개발자에게 필요한 만큼 단순하거나 복잡하게 +android.view.View}와 {@link android.view.ViewGroup} 객체의 계층으로 정의됩니다. 각 보기 그룹은 +하위 보기를 체계화하는 투명한 컨테이너이고, +하위 보기는 UI의 일부분을 그리는 제어나 다른 위젯일 수 있습니다. +이 계층 트리는 개발자에게 필요한 만큼 단순하거나 복잡하게 만들 수 있습니다(다만 단순한 것이 성능에는 가장 좋습니다).

    -

    그림 1. 보기 계층을 나타낸 것으로, 이것이 +

    그림 1. 보기 계층을 나타낸 것으로, 이것이 UI 레이아웃을 정의합니다.

    -

    레이아웃을 선언하려면 코드의 {@link android.view.View} 객체를 인스턴트화하고 트리를 구축하기 시작하면 되지만, -레이아웃을 정의하는 가장 쉽고 효과적인 방법은 XML 파일을 사용하는 것입니다. +

    레이아웃을 선언하려면 코드의 {@link android.view.View} 객체를 인스턴트화하고 트리를 구축하기 시작하면 되지만, +레이아웃을 정의하는 가장 쉽고 효과적인 방법은 XML 파일을 사용하는 것입니다. XML은 HTML과 유사한, 인간이 읽을 수 있는 레이아웃 구조를 제공합니다.

    -

    보기의 XML 요소 이름은 해당 요소가 나타내는 각각의 Android 클래스를 따릅니다. 말하자면 +

    보기의 XML 요소 이름은 해당 요소가 나타내는 각각의 Android 클래스를 따릅니다. 말하자면 <TextView> 요소가 UI에서 {@link android.widget.TextView} 위젯을 생성하고, -<LinearLayout> 요소는 {@link android.widget.LinearLayout} 보기 +<LinearLayout> 요소는 {@link android.widget.LinearLayout} 보기 그룹을 생성하는 것입니다.

    예를 들어, 텍스트 보기와 버튼 하나가 있는 단순한 수직 레이아웃은 이런 모습을 띱니다.

     <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    -              android:layout_width="fill_parent" 
    +              android:layout_width="fill_parent"
                   android:layout_height="fill_parent"
                   android:orientation="vertical" >
         <TextView android:id="@+id/text"
    @@ -53,19 +53,19 @@ XML은 HTML과 유사한, 인간이 읽을 수 있는 레이아웃 구조를 제
     </LinearLayout>
     
    -

    앱에 레이아웃 리소스를 로드하면 Android가 레이아웃의 각 노드를 초기화하여 -추가 동작을 정의하거나, 객체 상태를 쿼리 또는 레이아웃을 수정하는 데 쓸 수 있는 런타임 객체로 +

    앱에 레이아웃 리소스를 로드하면 Android가 레이아웃의 각 노드를 초기화하여 +추가 동작을 정의하거나, 객체 상태를 쿼리 또는 레이아웃을 수정하는 데 쓸 수 있는 런타임 객체로 초기화합니다.

    -

    UI 레이아웃 생성에 대한 완전한 가이드는 XML +

    UI 레이아웃 생성에 대한 완전한 가이드는 XML 레이아웃을 참조하십시오. - +

    사용자 인터페이스 구성 요소

    UI를 구축할 때 모두 {@link android.view.View} 및 {@link -android.view.ViewGroup} 객체를 사용해야 하는 것은 아닙니다. Android가 표준형 UI 레이아웃을 제공하는 앱 구성 요소를 여러 개 제공하고 있으니, -개발자 여러분은 이에 대한 콘텐츠만 정의하면 됩니다. 이와 같은 UI 구성 요소에는 각각 +android.view.ViewGroup} 객체를 사용해야 하는 것은 아닙니다. Android가 표준형 UI 레이아웃을 제공하는 앱 구성 요소를 여러 개 제공하고 있으니, +개발자 여러분은 이에 대한 콘텐츠만 정의하면 됩니다. 이와 같은 UI 구성 요소에는 각각 고유한 API 세트가 있습니다. 이들은 작업 모음, 대화상태 알림 등 각각 다른 문서에서 설명하였습니다.

    diff --git a/docs/html-intl/intl/ko/guide/topics/ui/settings.jd b/docs/html-intl/intl/ko/guide/topics/ui/settings.jd index 36204e03ecf5e..01b62ed6783a2 100644 --- a/docs/html-intl/intl/ko/guide/topics/ui/settings.jd +++ b/docs/html-intl/intl/ko/guide/topics/ui/settings.jd @@ -65,13 +65,13 @@ page.tags=preference,preferenceactivity,preferencefragment -

    애플리케이션에는 종종 설정이 포함되어 있어 사용자가 앱 기능과 행동을 수정할 수 있게 해줍니다. 예를 들어 -몇몇 앱은 사용자에게 알림을 활성화할지 여부를 지정하거나 애플리케이션이 +

    애플리케이션에는 종종 설정이 포함되어 있어 사용자가 앱 기능과 행동을 수정할 수 있게 해줍니다. 예를 들어 +몇몇 앱은 사용자에게 알림을 활성화할지 여부를 지정하거나 애플리케이션이 클라우드와 데이터를 동기화할 빈도를 지정할 수 있게 해줍니다.

    -

    자신의 앱에 설정을 제공하고자 하는 경우, Android의 -{@link android.preference.Preference} API를 사용하여 다른 Android 앱(시스템 설정 포함)의 사용자 환경과 -일관성을 유지하는 인터페이스를 구축할 수 있게 해야 합니다. 이 문서에서는 +

    자신의 앱에 설정을 제공하고자 하는 경우, Android의 +{@link android.preference.Preference} API를 사용하여 다른 Android 앱(시스템 설정 포함)의 사용자 환경과 +일관성을 유지하는 인터페이스를 구축할 수 있게 해야 합니다. 이 문서에서는 {@link android.preference.Preference} API를 사용하여 앱 설정을 구축하는 방법을 설명합니다.

    @@ -81,8 +81,8 @@ page.tags=preference,preferenceactivity,preferencefragment -

    그림 1. Android 메시지 앱의 설정에서 가져온 -스크린샷입니다. {@link android.preference.Preference}가 정의한 항목을 선택하면 +

    그림 1. Android 메시지 앱의 설정에서 가져온 +스크린샷입니다. {@link android.preference.Preference}가 정의한 항목을 선택하면 인터페이스가 열려 설정을 변경할 수 있게 됩니다.

    @@ -90,24 +90,24 @@ page.tags=preference,preferenceactivity,preferencefragment

    개요

    -

    사용자 인터페이스를 구축할 때에는 {@link android.view.View} 객체를 사용하지만, 설정은 그 대신 -{@link android.preference.Preference} 클래스의 다양한 하위 클래스를 사용하여 구축합니다. +

    사용자 인터페이스를 구축할 때에는 {@link android.view.View} 객체를 사용하지만, 설정은 그 대신 +{@link android.preference.Preference} 클래스의 다양한 하위 클래스를 사용하여 구축합니다. 이와 같은 하위 클래스는 XML 파일에서 선언합니다.

    -

    {@link android.preference.Preference} 객체는 하나의 설정을 이루는 기본 -단위입니다. 각각의 {@link android.preference.Preference}는 목록의 항목으로 +

    {@link android.preference.Preference} 객체는 하나의 설정을 이루는 기본 +단위입니다. 각각의 {@link android.preference.Preference}는 목록의 항목으로 나타나며 사용자가 설정을 수정하기에 적절한 UI를 제공합니다. 예를 들어 {@link android.preference.CheckBoxPreference}는 확인란을 표시하는 목록 항목을 만들고, {@link android.preference.ListPreference}는 선택 목록이 있는 대화를 여는 항목을 만듭니다.

    -

    각각의 {@link android.preference.Preference}를 추가할 때마다 상응하는 키-값 쌍이 있어 +

    각각의 {@link android.preference.Preference}를 추가할 때마다 상응하는 키-값 쌍이 있어 시스템이 이를 사용하여 해당 설정을 앱의 설정에 대한 기본 {@link android.content.SharedPreferences} -파일에 저장합니다. 사용자가 설정을 변경하면 시스템이 -{@link android.content.SharedPreferences} 파일에 있는 상응하는 값을 개발자 대신 업데이트합니다. 개발자가 직접 -연관된 {@link android.content.SharedPreferences} 파일과 상호 작용을 해야 하는 경우는 +파일에 저장합니다. 사용자가 설정을 변경하면 시스템이 +{@link android.content.SharedPreferences} 파일에 있는 상응하는 값을 개발자 대신 업데이트합니다. 개발자가 직접 +연관된 {@link android.content.SharedPreferences} 파일과 상호 작용을 해야 하는 경우는 사용자의 설정을 기반으로 앱의 동작을 결정하기 위해 값을 읽어야 할 때뿐입니다.

    -

    각 설정에 대하여 {@link android.content.SharedPreferences}에 저장된 값은 다음과 같은 +

    각 설정에 대하여 {@link android.content.SharedPreferences}에 저장된 값은 다음과 같은 데이터 유형 중 한 가지를 취할 수 있습니다.

      @@ -119,31 +119,31 @@ android.preference.ListPreference}는 선택 목록이 있는 대화를 여는
    • String {@link java.util.Set}
    -

    앱의 설정 UI는 -{@link android.view.View} 객체 대신 -{@link android.preference.Preference} 객체를 사용하여 구축되기 때문에, 목록 설정을 표시하려면 특수 {@link android.app.Activity} 또는 +

    앱의 설정 UI는 +{@link android.view.View} 객체 대신 +{@link android.preference.Preference} 객체를 사용하여 구축되기 때문에, 목록 설정을 표시하려면 특수 {@link android.app.Activity} 또는 {@link android.app.Fragment} 하위 클래스를 사용해야 합니다.

      -
    • 앱이 Android 3.0 이전 버전(API 레벨 10 이하)을 지원하는 경우, 액티비티를 구축할 때 +
    • 앱이 Android 3.0 이전 버전(API 레벨 10 이하)을 지원하는 경우, 액티비티를 구축할 때 {@link android.preference.PreferenceActivity} 클래스의 확장으로 구축해야 합니다.
    • -
    • Android 3.0 이후의 경우에는 대신 기존의 {@link android.app.Activity}를 -사용해야 합니다. 이것은 앱 설정을 표시하는 {@link android.preference.PreferenceFragment}를 호스팅합니다. -하지만, 여러 개의 설정 그룹이 있는 경우 {@link android.preference.PreferenceActivity}를 사용하여 +
    • Android 3.0 이후의 경우에는 대신 기존의 {@link android.app.Activity}를 +사용해야 합니다. 이것은 앱 설정을 표시하는 {@link android.preference.PreferenceFragment}를 호스팅합니다. +하지만, 여러 개의 설정 그룹이 있는 경우 {@link android.preference.PreferenceActivity}를 사용하여 대형 화면에 맞는 창 두 개짜리 레이아웃을 만들 수도 있습니다.

    {@link android.preference.PreferenceActivity}와 {@link -android.preference.PreferenceFragment}의 인스턴스를 설정하는 방법은 기본 설정 액티비티 만들기기본 설정 +android.preference.PreferenceFragment}의 인스턴스를 설정하는 방법은 기본 설정 액티비티 만들기기본 설정 프래그먼트 사용하기에 관련된 섹션에서 논합니다.

    기본 설정

    앱에 대한 설정은 모두 {@link -android.preference.Preference} 클래스의 특정 하위 클래스로 표현됩니다. 각 하위 클래스에 핵심 속성이 한 세트씩 포함되어 있어 -설정의 제목과 기본 값 등과 같은 것을 지정할 수 있게 해줍니다. 각 하위 클래스는 또한 자신만의 -특수 속성과 사용자 인터페이스도 제공합니다. 예를 들어, 그림 1에서는 메시지 앱의 설정에서 +android.preference.Preference} 클래스의 특정 하위 클래스로 표현됩니다. 각 하위 클래스에 핵심 속성이 한 세트씩 포함되어 있어 +설정의 제목과 기본 값 등과 같은 것을 지정할 수 있게 해줍니다. 각 하위 클래스는 또한 자신만의 +특수 속성과 사용자 인터페이스도 제공합니다. 예를 들어, 그림 1에서는 메시지 앱의 설정에서 가져온 스크린샷을 나타낸 것입니다. 설정 화면에 있는 각 목록 항목은 각기 서로 다른 {@link android.preference.Preference} 객체로 지원됩니다.

    @@ -151,11 +151,11 @@ android.preference.Preference} 객체로 지원됩니다.

    {@link android.preference.CheckBoxPreference}
    -
    활성화되었거나 비활성화된 설정에 대한 확인란이 있는 항목을 표시합니다. 저장된 값은 +
    활성화되었거나 비활성화된 설정에 대한 확인란이 있는 항목을 표시합니다. 저장된 값은 부울입니다(확인란이 선택된 경우 true).
    {@link android.preference.ListPreference}
    -
    무선 버튼 목록이 있는 대화를 엽니다. 저장된 값은 +
    무선 버튼 목록이 있는 대화를 엽니다. 저장된 값은 지원되는 값 유형(위에 목록으로 나열) 중 어느 것이라도 될 수 있습니다.
    {@link android.preference.EditTextPreference}
    @@ -166,36 +166,36 @@ java.lang.String}입니다.

    다른 모든 하위 클래스와 이에 상응하는 속성의 목록을 보려면 {@link android.preference.Preference} 클래스를 참조하십시오.

    -

    물론 기본 제공 클래스만으로는 필요한 것을 모두 충족할 수 없고 앱에 무언가 좀 더 특수한 것이 +

    물론 기본 제공 클래스만으로는 필요한 것을 모두 충족할 수 없고 앱에 무언가 좀 더 특수한 것이 필요할 수도 있습니다. 예를 들어 플랫폼은 현재 숫자나 날짜를 선택할 수 있는 {@link -android.preference.Preference} 클래스를 제공하지 않습니다. 따라서 개발자 나름대로 +android.preference.Preference} 클래스를 제공하지 않습니다. 따라서 개발자 나름대로 {@link android.preference.Preference} 하위 클래스를 정의해야 할 수도 있습니다. 이 작업을 수행하는 데 유용한 내용인 사용자 지정 기본 설정 구축하기에 관한 섹션을 참조하십시오.

    XML로 기본 설정 정의하기

    -

    새로운 {@link android.preference.Preference} 객체를 런타임에 인스턴트화하는 것도 가능하지만, +

    새로운 {@link android.preference.Preference} 객체를 런타임에 인스턴트화하는 것도 가능하지만, 설정 목록을 정의할 때에는 {@link android.preference.Preference} -객체의 계층과 함께 XML을 사용해야 합니다. 설정 컬렉션을 정의하는 데 XM 파일을 사용하는 것이 선호되는 이유는 이 파일이 -읽기 쉬운 구조를 제공하여 업데이트가 단순하기 때문입니다. 또한, 앱의 설정은 보통 +객체의 계층과 함께 XML을 사용해야 합니다. 설정 컬렉션을 정의하는 데 XM 파일을 사용하는 것이 선호되는 이유는 이 파일이 +읽기 쉬운 구조를 제공하여 업데이트가 단순하기 때문입니다. 또한, 앱의 설정은 보통 미리 정의되어 있습니다. 다만 개발자도 여전히 런타임에 설정 컬렉션을 수정할 수 있습니다.

    -

    각 {@link android.preference.Preference} 하위 클래스는 클래스 이름에 일치하는 XML 요소로 +

    각 {@link android.preference.Preference} 하위 클래스는 클래스 이름에 일치하는 XML 요소로 선언하면 됩니다. 예를 들면 {@code <CheckBoxPreference>}가 이에 해당됩니다.

    -

    이 XML 파일은 반드시 {@code res/xml/} 디렉터리에 저장해야 합니다. 파일의 이름은 무엇이든 원하는 대로 지정할 수 있지만, -일반적으로는 {@code preferences.xml}이라고 명명합니다. 파일은 하나만 필요한 것이 보통입니다. -왜냐하면 계층에 있는 분기(자신만의 설정 목록을 엶)는 +

    이 XML 파일은 반드시 {@code res/xml/} 디렉터리에 저장해야 합니다. 파일의 이름은 무엇이든 원하는 대로 지정할 수 있지만, +일반적으로는 {@code preferences.xml}이라고 명명합니다. 파일은 하나만 필요한 것이 보통입니다. +왜냐하면 계층에 있는 분기(자신만의 설정 목록을 엶)는 {@link android.preference.PreferenceScreen}의 중첩된 인스턴스를 사용하여 선언되기 때문입니다.

    -

    참고: 설정에 다중 창 레이아웃을 만들고자 하는 경우, +

    참고: 설정에 다중 창 레이아웃을 만들고자 하는 경우, 각 프래그먼트에 대해 별도의 XML 파일이 필요합니다.

    XML 파일의 루트 노드는 반드시 {@link android.preference.PreferenceScreen <PreferenceScreen>} 요소여야 합니다. 바로 이 요소 내에 각 {@link -android.preference.Preference}를 추가하는 것입니다. -{@link android.preference.PreferenceScreen <PreferenceScreen>} 요소 내에 추가하는 각 하위는 설정 목록에서 +android.preference.Preference}를 추가하는 것입니다. +{@link android.preference.PreferenceScreen <PreferenceScreen>} 요소 내에 추가하는 각 하위는 설정 목록에서 각기 항목 하나씩으로 나타납니다.

    예:

    @@ -224,11 +224,11 @@ android.preference.ListPreference}가 하나씩 있습니다. 두 항목 모두
    {@code android:key}
    -
    이 속성은 데이터 값을 유지하는 기본 설정에 필수입니다. 이것은 고유키(문자)를 +
    이 속성은 데이터 값을 유지하는 기본 설정에 필수입니다. 이것은 고유키(문자)를 나타내며, 시스템이 이것을 사용하여 이 설정의 값을 {@link -android.content.SharedPreferences}에 저장합니다. -

    이 속성이 필요하지 않은 인스턴스는 기본 설정이 -{@link android.preference.PreferenceCategory} 또는 {@link android.preference.PreferenceScreen}인 경우, 또는 +android.content.SharedPreferences}에 저장합니다. +

    이 속성이 필요하지 않은 인스턴스는 기본 설정이 +{@link android.preference.PreferenceCategory} 또는 {@link android.preference.PreferenceScreen}인 경우, 또는 기본 설정이 {@link android.content.Intent}를 호출할 것을 나타내거나({@code <intent>} 요소로) {@link android.app.Fragment}를 표시하도록 지정하는 경우({@code android:fragment} 속성으로)뿐입니다.

    @@ -236,7 +236,7 @@ android:fragment} 속성으로)뿐입니다.

    이것은 설정에 대하여 사용자가 볼 수 있는 이름을 제공합니다.
    {@code android:defaultValue}
    이것은 시스템이 {@link -android.content.SharedPreferences} 파일에 설정해야 하는 초기 값을 나타냅니다. 모든 설정에 기본 값을 제공해야 +android.content.SharedPreferences} 파일에 설정해야 하는 초기 값을 나타냅니다. 모든 설정에 기본 값을 제공해야 합니다.
    @@ -248,21 +248,21 @@ android.preference.Preference}(및 각각의 하위 클래스) 관련 문서를

    그림 2. 제목이 있는 설정 카테고리입니다.
    1. 카테고리는 {@link -android.preference.PreferenceCategory <PreferenceCategory>} 요소가 지정합니다.
    2. 제목은 +android.preference.PreferenceCategory <PreferenceCategory>} 요소가 지정합니다.
    2. 제목은 {@code android:title} 속성으로 지정합니다.

    -

    설정 목록이 약 10개 항목을 초과하면 제목을 추가하여 -설정 그룹을 정의하거나, 해당 그룹을 별도의 +

    설정 목록이 약 10개 항목을 초과하면 제목을 추가하여 +설정 그룹을 정의하거나, 해당 그룹을 별도의 화면에 표시하는 것이 좋을 수도 있습니다. 이러한 옵션은 다음 섹션에 설명되어 있습니다.

    설정 그룹 만들기

    -

    10개 이상의 설정 목록을 제시하는 경우, 사용자가 -이들을 둘러보고 이해하며 처리하는 데 어려움을 겪을 수 있습니다. 이 문제를 해결하려면 -설정의 일부 또는 모두를 그룹으로 나누어 사실상 하나의 긴 목록을 여러 개의 더 짧은 목록으로 +

    10개 이상의 설정 목록을 제시하는 경우, 사용자가 +이들을 둘러보고 이해하며 처리하는 데 어려움을 겪을 수 있습니다. 이 문제를 해결하려면 +설정의 일부 또는 모두를 그룹으로 나누어 사실상 하나의 긴 목록을 여러 개의 더 짧은 목록으로 바꿔주면 됩니다. 관련된 설정 그룹 하나를 나타낼 때에는 다음과 같은 두 가지 방식 중 하나를 택하면 됩니다.

    -

    이와 같은 그룹화 기법 중 하나 또는 둘 모두를 사용하여 앱의 설정을 조직화할 수 있습니다. 어느 것을 -사용할지, 설정을 어떻게 나눌지 결정할 때에는 Android +

    이와 같은 그룹화 기법 중 하나 또는 둘 모두를 사용하여 앱의 설정을 조직화할 수 있습니다. 어느 것을 +사용할지, 설정을 어떻게 나눌지 결정할 때에는 Android 디자인의 설정 가이드에 있는 지침을 따라야 합니다.

    제목 사용하기

    -

    여러 개의 설정 그룹 사이에 구분선과 제목을 제공하고자 하는 경우(그림 2에 표시된 것과 같이), +

    여러 개의 설정 그룹 사이에 구분선과 제목을 제공하고자 하는 경우(그림 2에 표시된 것과 같이), 각 {@link android.preference.Preference} 객체 그룹을 {@link android.preference.PreferenceCategory} 내부에 배치합니다.

    @@ -285,7 +285,7 @@ android.preference.PreferenceCategory} 내부에 배치합니다.

     <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    -    <PreferenceCategory 
    +    <PreferenceCategory
             android:title="@string/pref_sms_storage_title"
             android:key="pref_key_storage_settings">
             <CheckBoxPreference
    @@ -293,12 +293,12 @@ android.preference.PreferenceCategory} 내부에 배치합니다.

    android:summary="@string/pref_summary_auto_delete" android:title="@string/pref_title_auto_delete" android:defaultValue="false"... /> - <Preference + <Preference android:key="pref_key_sms_delete_limit" android:dependency="pref_key_auto_delete" android:summary="@string/pref_summary_delete_limit" android:title="@string/pref_title_sms_delete"... /> - <Preference + <Preference android:key="pref_key_mms_delete_limit" android:dependency="pref_key_auto_delete" android:summary="@string/pref_summary_delete_limit" @@ -311,13 +311,13 @@ android.preference.PreferenceCategory} 내부에 배치합니다.

    보조 화면 사용하기

    -

    설정 그룹 여러 개를 보조 화면에 배치하고자 하는 경우(그림 3에 표시된 것과 같이), 해당 +

    설정 그룹 여러 개를 보조 화면에 배치하고자 하는 경우(그림 3에 표시된 것과 같이), 해당 {@link android.preference.Preference} 객체 그룹을 {@link android.preference.PreferenceScreen} 안에 배치합니다.

    그림 3. 설정 보조 화면입니다. {@code -<PreferenceScreen>} 요소가 +<PreferenceScreen>} 요소가 항목을 만들며, 이 항목이 선택되면 별도의 목록이 열려 중첩된 설정을 표시합니다.

    예:

    @@ -352,7 +352,7 @@ android.preference.PreferenceScreen} 안에 배치합니다.

    인텐트 사용하기

    -

    어떤 경우에는 기본 설정 항목을 사용하여 설정 화면 대신 여러 가지 액티비티를 +

    어떤 경우에는 기본 설정 항목을 사용하여 설정 화면 대신 여러 가지 액티비티를 열고자 할 수도 있습니다. 예를 들어 웹 브라우저를 열어 웹 페이지를 보는 것이 이에 해당됩니다. 사용자가 기본 설정 항목을 선택할 때 {@link android.content.Intent}를 호출하도록 하려면, {@code <intent>} 요소를 상응하는 {@code <Preference>} 요소의 하위로 추가하면 됩니다.

    @@ -392,18 +392,18 @@ android.content.Intent#setComponent setComponent()} 메서드를 따릅니다.설정을 액티비티에서 표시하려면 {@link android.preference.PreferenceActivity} 클래스를 확장하면 됩니다. 이것은 일반적인 {@link android.app.Activity} 클래스 확장의 일종입니다. 이는 {@link -android.preference.Preference} 객체의 계층에 기반한 설정 목록을 표시합니다. {@link android.preference.PreferenceActivity}는 +android.preference.Preference} 객체의 계층에 기반한 설정 목록을 표시합니다. {@link android.preference.PreferenceActivity}는 사용자가 변경 작업을 하면 각 {@link android.preference.Preference}와 연관된 설정을 유지합니다.

    -

    참고: Android 3.0 이상에 맞춰 애플리케이션을 개발하는 경우, -대신 {@link android.preference.PreferenceFragment}를 사용해야 합니다. 다음 섹션의 +

    참고: Android 3.0 이상에 맞춰 애플리케이션을 개발하는 경우, +대신 {@link android.preference.PreferenceFragment}를 사용해야 합니다. 다음 섹션의 기본 설정 프래그먼트 사용하기 관련 내용을 참조하십시오.

    여기서 기억해야 할 가장 중요한 점은 {@link android.preference.PreferenceActivity#onCreate onCreate()} 콜백 중에 보기 레이아웃을 로딩해서는 안 된다는 것입니다. 그 대신 {@link -android.preference.PreferenceActivity#addPreferencesFromResource addPreferencesFromResource()}를 호출하여 -XML 파일에서 선언한 기본 설정을 액티비티에 추가합니다. 예를 들어 다음은 기능적인 +android.preference.PreferenceActivity#addPreferencesFromResource addPreferencesFromResource()}를 호출하여 +XML 파일에서 선언한 기본 설정을 액티비티에 추가합니다. 예를 들어 다음은 기능적인 {@link android.preference.PreferenceActivity}에 필요한 가장 최소한의 코드를 나타낸 것입니다.

    @@ -416,11 +416,11 @@ public class SettingsActivity extends PreferenceActivity {
     }
     
    -

    사실 이 코드만으로 몇몇 앱에는 충분합니다. 사용자가 기본 설정을 수정하자마자 -시스템이 해당 변경을 기본 {@link android.content.SharedPreferences} 파일에 저장하여, -사용자의 설정을 확인해야 할 때 다른 애플리케이션 구성 요소가 이를 읽을 수 있도록 하기 때문입니다. 하지만 +

    사실 이 코드만으로 몇몇 앱에는 충분합니다. 사용자가 기본 설정을 수정하자마자 +시스템이 해당 변경을 기본 {@link android.content.SharedPreferences} 파일에 저장하여, +사용자의 설정을 확인해야 할 때 다른 애플리케이션 구성 요소가 이를 읽을 수 있도록 하기 때문입니다. 하지만 대다수의 앱은 기본 설정에 일어나는 변경을 수신 대기하기 위해 약간의 코드가 더 필요합니다. -{@link android.content.SharedPreferences} 파일에 일어나는 변경을 수신 대기하는 데 관한 +{@link android.content.SharedPreferences} 파일에 일어나는 변경을 수신 대기하는 데 관한 자세한 정보는 기본 설정 읽기에 관한 섹션을 참조하십시오.

    @@ -430,17 +430,17 @@ public class SettingsActivity extends PreferenceActivity {

    Android 3.0(API 레벨 11) 이상에 맞춰 개발하는 경우, {@link android.preference.PreferenceFragment}를 사용하여 {@link android.preference.Preference} -객체 목록을 표시해야 합니다. {@link android.preference.PreferenceFragment}는 모든 액티비티에 추가할 수 있습니다. 즉, +객체 목록을 표시해야 합니다. {@link android.preference.PreferenceFragment}는 모든 액티비티에 추가할 수 있습니다. 즉, {@link android.preference.PreferenceActivity}를 사용하지 않아도 됩니다.

    -

    프래그먼트는 액티비티만 -사용하는 것에 비해 애플리케이션에 보다 유연한 아키텍처를 제공하며, 이는 구축하는 +

    프래그먼트는 액티비티만 +사용하는 것에 비해 애플리케이션에 보다 유연한 아키텍처를 제공하며, 이는 구축하는 액티비티의 종류와 무관하게 적용됩니다. 따라서 설정 표시를 제어하는 데에는 {@link android.preference.PreferenceFragment}를 {@link android.preference.PreferenceActivity} 대신 사용하는 방안을 권장합니다(가능한 경우).

    {@link android.preference.PreferenceFragment} 구현은 매우 간단합니다. -{@link android.preference.PreferenceFragment#onCreate onCreate()} 메서드를 정의하여 기본 설정 파일을 +{@link android.preference.PreferenceFragment#onCreate onCreate()} 메서드를 정의하여 기본 설정 파일을 {@link android.preference.PreferenceFragment#addPreferencesFromResource addPreferencesFromResource()}로 로딩하도록 하기만 하면 됩니다. 예:

    @@ -457,7 +457,7 @@ public static class SettingsFragment extends PreferenceFragment { }
    -

    그런 다음 이 프래그먼트를 {@link android.app.Activity}에 추가하기만 하면 되고, 이는 다른 모든 +

    그런 다음 이 프래그먼트를 {@link android.app.Activity}에 추가하기만 하면 되고, 이는 다른 모든 {@link android.app.Fragment}에서와 마찬가지입니다. 예:

    @@ -474,24 +474,24 @@ public class SettingsActivity extends Activity {
     }
     
    -

    참고: {@link android.preference.PreferenceFragment}에는 자신만의 +

    참고: {@link android.preference.PreferenceFragment}에는 자신만의 {@link android.content.Context} 객체가 없습니다. {@link android.content.Context} -객체가 필요한 경우, {@link android.app.Fragment#getActivity()}를 호출하면 됩니다. 하지만, -{@link android.app.Fragment#getActivity()}를 호출하는 것은 프래그먼트가 액티비티에 첨부되어 있는 경우만으로 국한시켜야 한다는 점을 유의하십시오. 프래그먼트가 +객체가 필요한 경우, {@link android.app.Fragment#getActivity()}를 호출하면 됩니다. 하지만, +{@link android.app.Fragment#getActivity()}를 호출하는 것은 프래그먼트가 액티비티에 첨부되어 있는 경우만으로 국한시켜야 한다는 점을 유의하십시오. 프래그먼트가 아직 첨부되지 않았거나 수명 주기가 끝날 무렵 분리된 경우, {@link android.app.Fragment#getActivity()}가 null을 반환합니다.

    설정 기본 값

    -

    여러분이 만드는 기본 설정은 애플리케이션에 중요한 동작을 정의하는 경우가 많을 것입니다. 따라서 -연관된 {@link android.content.SharedPreferences} 파일을 -각 {@link android.preference.Preference}에 대한 기본 값으로 초기화하여 사용자가 애플리케이션을 처음 열 때 +

    여러분이 만드는 기본 설정은 애플리케이션에 중요한 동작을 정의하는 경우가 많을 것입니다. 따라서 +연관된 {@link android.content.SharedPreferences} 파일을 +각 {@link android.preference.Preference}에 대한 기본 값으로 초기화하여 사용자가 애플리케이션을 처음 열 때 적용하는 것이 중요합니다.

    가장 먼저 해야 할 일은 XML 파일 내의 각 {@link android.preference.Preference} -객체에 대해 기본 값을 지정하는 것입니다. 이때 {@code android:defaultValue} 속성을 사용합니다. 이 값은 상응하는 +객체에 대해 기본 값을 지정하는 것입니다. 이때 {@code android:defaultValue} 속성을 사용합니다. 이 값은 상응하는 {@link android.preference.Preference} 객체에 대해 적절한 어느 데이터 유형이라도 될 수 있습니다. 예:

    @@ -507,8 +507,8 @@ android.preference.Preference} ... /> -

    그런 다음, 애플리케이션의 기본 액티비티에 있는 {@link android.app.Activity#onCreate onCreate()} -메서드로부터—또한 사용자가 애플리케이션에 처음으로 들어올 통로가 될 수 있는 +

    그런 다음, 애플리케이션의 기본 액티비티에 있는 {@link android.app.Activity#onCreate onCreate()} +메서드로부터—또한 사용자가 애플리케이션에 처음으로 들어올 통로가 될 수 있는 다른 모든 액티비티도 포함—{@link android.preference.PreferenceManager#setDefaultValues setDefaultValues()}를 호출합니다.

    @@ -516,9 +516,9 @@ setDefaultValues()}를 호출합니다.

    PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false); -

    이것을 {@link android.app.Activity#onCreate onCreate()} 중에 호출하면 -애플리케이션이 기본 설정으로 적절히 초기화되도록 보장할 수 있습니다. 이것은 애플리케이션이 -몇 가지 동작을 결정하기 위해 읽어야 할 수도 있습니다(예를 들어 셀룰러 네트워크에서 데이터를 +

    이것을 {@link android.app.Activity#onCreate onCreate()} 중에 호출하면 +애플리케이션이 기본 설정으로 적절히 초기화되도록 보장할 수 있습니다. 이것은 애플리케이션이 +몇 가지 동작을 결정하기 위해 읽어야 할 수도 있습니다(예를 들어 셀룰러 네트워크에서 데이터를 다운로드할지 여부 등).

    이 메서드는 다음과 같은 세 개의 인수를 취합니다.

    @@ -526,73 +526,73 @@ PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);
  • 애플리케이션 {@link android.content.Context}.
  • 기본 값을 설정하고자 하는 기본 설정 XML 파일에 대한 리소스 ID입니다.
  • 기본 값을 한 번 이상 설정해야 하는지 여부를 나타내는 부울 값입니다. -

    false인 경우, 시스템은 이 메서드가 전에 한 번도 호출된 적이 없을 경우에만 +

    false인 경우, 시스템은 이 메서드가 전에 한 번도 호출된 적이 없을 경우에만 기본 값을 설정합니다(아니면 기본 값을 공유한 기본 설정 파일에 있는 {@link android.preference.PreferenceManager#KEY_HAS_SET_DEFAULT_VALUES} 가 안전합니다).

  • -

    세 번째 인수를 false로 설정해 두는 한 이 메서드를 액티비티가 시작될 때마다 -안전하게 호출할 수 있으며, 그렇게 해도 사용자의 저장된 기본 설정을 기본값으로 초기화하여 -재정의하지 않습니다. 하지만 이를 true로 설정하면, 이전의 모든 값을 +

    세 번째 인수를 false로 설정해 두는 한 이 메서드를 액티비티가 시작될 때마다 +안전하게 호출할 수 있으며, 그렇게 해도 사용자의 저장된 기본 설정을 기본값으로 초기화하여 +재정의하지 않습니다. 하지만 이를 true로 설정하면, 이전의 모든 값을 기본 값으로 재정의하게 됩니다.

    기본 설정 헤더 사용하기

    -

    드문 경우지만 설정을 디자인할 때 첫 화면에는 -보조 화면 목록만 표시하도록 하고자 할 수도 있습니다(예: 시스템 설정 앱, -그림 4와 5 참조). 그러한 디자인을 Android 3.0 이상을 대상으로 개발하는 경우, Android 3.0에 있는 -새로운 "헤더" 기능을 사용해야 합니다. 이것이 중첩된 +

    드문 경우지만 설정을 디자인할 때 첫 화면에는 +보조 화면 목록만 표시하도록 하고자 할 수도 있습니다(예: 시스템 설정 앱, +그림 4와 5 참조). 그러한 디자인을 Android 3.0 이상을 대상으로 개발하는 경우, Android 3.0에 있는 +새로운 "헤더" 기능을 사용해야 합니다. 이것이 중첩된 {@link android.preference.PreferenceScreen} 요소를 사용하여 보조 화면을 구축하는 방안을 대신합니다.

    헤더를 사용하여 설정을 구축하려면 다음과 같이 해야 합니다.

    1. 각 설정 그룹을 별개의 {@link -android.preference.PreferenceFragment} 인스턴스로 구분합니다. 다시 말해, 설정 그룹마다 별도의 XML 파일이 하나씩 있어야 한다는 +android.preference.PreferenceFragment} 인스턴스로 구분합니다. 다시 말해, 설정 그룹마다 별도의 XML 파일이 하나씩 있어야 한다는 뜻입니다.
    2. -
    3. 각 설정 그룹을 목록으로 나열하는 XML 헤더 파일을 생성하고 어느 프래그먼트에 +
    4. 각 설정 그룹을 목록으로 나열하는 XML 헤더 파일을 생성하고 어느 프래그먼트에 상응하는 설정 목록이 들어있는지 선언합니다.
    5. {@link android.preference.PreferenceActivity} 클래스를 확장하여 설정을 호스팅하도록 합니다.
    6. {@link -android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} 콜백을 구현하여 헤더 파일을 +android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} 콜백을 구현하여 헤더 파일을 나타냅니다.
    -

    이 디자인을 사용하는 데 있어 커다란 이점은 {@link android.preference.PreferenceActivity}가 +

    이 디자인을 사용하는 데 있어 커다란 이점은 {@link android.preference.PreferenceActivity}가 (앱이) 대형 화면에서 실행될 때 그림 4에서 나타낸 것과 같이 창 두 개짜리 레이아웃을 자동으로 표시한다는 것입니다.

    -

    애플리케이션이 Android 3.0 이전 버전을 지원한다 하더라도 애플리케이션이 -{@link android.preference.PreferenceFragment}를 사용하여 -신형 기기에서 창 두 개짜리 표시를 지원하도록 하면서도 구형 기기에서는 일반적인 다중 화면 계층을 -여전히 지원하도록 할 수도 있습니다(기본 설정 헤더로 +

    애플리케이션이 Android 3.0 이전 버전을 지원한다 하더라도 애플리케이션이 +{@link android.preference.PreferenceFragment}를 사용하여 +신형 기기에서 창 두 개짜리 표시를 지원하도록 하면서도 구형 기기에서는 일반적인 다중 화면 계층을 +여전히 지원하도록 할 수도 있습니다(기본 설정 헤더로 이전 버전 지원하기를 참조하십시오).

    -

    그림 4. 헤더가 있는 창 두 개짜리 레이아웃입니다.
    1. 헤더는 -XML 헤더 파일로 정의됩니다.
    2. 각 설정 그룹은 -{@link android.preference.PreferenceFragment}가 정의하며, 이는 헤더 파일에 있는 {@code <header>} 요소가 +

    그림 4. 헤더가 있는 창 두 개짜리 레이아웃입니다.
    1. 헤더는 +XML 헤더 파일로 정의됩니다.
    2. 각 설정 그룹은 +{@link android.preference.PreferenceFragment}가 정의하며, 이는 헤더 파일에 있는 {@code <header>} 요소가 지정합니다.

    -

    그림 5. 설정 헤더가 있는 핸드셋 기기입니다. 항목을 선택하면 -연관된 {@link android.preference.PreferenceFragment}가 헤더를 +

    그림 5. 설정 헤더가 있는 핸드셋 기기입니다. 항목을 선택하면 +연관된 {@link android.preference.PreferenceFragment}가 헤더를 대체합니다.

    헤더 파일 만들기

    -

    헤더 목록에 있는 각 설정 그룹은 루트 {@code <preference-headers>} +

    헤더 목록에 있는 각 설정 그룹은 루트 {@code <preference-headers>} 요소 안에 있는 {@code <header>} 요소 하나로 나타냅니다. 예:

     <?xml version="1.0" encoding="utf-8"?>
     <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
    -    <header 
    +    <header
             android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentOne"
             android:title="@string/prefs_category_one"
             android:summary="@string/prefs_summ_category_one" />
    -    <header 
    +    <header
             android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentTwo"
             android:title="@string/prefs_category_two"
             android:summary="@string/prefs_summ_category_two" >
    @@ -607,12 +607,12 @@ android.preference.PreferenceFragment} 예를 선언하며 이는 사용자가 
     
     

    {@code <extras>} 요소를 사용하면 키-값 쌍을 {@link android.os.Bundle} 내의 프래그먼트에 전달할 수 있게 해줍니다. 이 프래그먼트가 인수를 검색하려면 {@link -android.app.Fragment#getArguments()}를 호출하면 됩니다. 인수를 프래그먼트에 전달하는 데에는 여러 가지 이유가 있을 수 있지만, +android.app.Fragment#getArguments()}를 호출하면 됩니다. 인수를 프래그먼트에 전달하는 데에는 여러 가지 이유가 있을 수 있지만, 한 가지 중요한 이유를 예로 들면 각 그룹에 대해 {@link -android.preference.PreferenceFragment}의 같은 하위 클래스를 재사용하고, 이 인수를 사용하여 해당 프래그먼트가 로딩해야 하는 +android.preference.PreferenceFragment}의 같은 하위 클래스를 재사용하고, 이 인수를 사용하여 해당 프래그먼트가 로딩해야 하는 기본 설정 XML 파일이 무엇인지 나타낼 수 있다는 점입니다.

    -

    예를 들어 다음은 여러 가지 설정 그룹에 재사용할 수 있는 프래그먼트입니다. 이것은 +

    예를 들어 다음은 여러 가지 설정 그룹에 재사용할 수 있는 프래그먼트입니다. 이것은 각 헤더가 {@code "settings"} 키로 {@code <extra>} 인수를 정의하는 경우를 나타낸 것입니다.

    @@ -636,7 +636,7 @@ public static class SettingsFragment extends PreferenceFragment {
     

    헤더 표시하기

    기본 설정 헤더를 표시하려면 {@link -android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} 콜백 메서드를 구현하고 +android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} 콜백 메서드를 구현하고 {@link android.preference.PreferenceActivity#loadHeadersFromResource loadHeadersFromResource()}를 호출해야 합니다. 예:

    @@ -654,56 +654,56 @@ android.preference.PreferenceFragment}를 엽니다.

    참고: 기본 설정 헤더를 사용하는 경우, {@link android.preference.PreferenceActivity}의 하위 클래스가 {@link -android.preference.PreferenceActivity#onCreate onCreate()} 메서드를 구현하지 않아도 됩니다. 액티비티에 대한 필수 작업은 +android.preference.PreferenceActivity#onCreate onCreate()} 메서드를 구현하지 않아도 됩니다. 액티비티에 대한 필수 작업은 헤더를 로딩하는 것뿐이기 때문입니다.

    기본 설정 헤더로 이전 버전 지원하기

    -

    애플리케이션이 Android 3.0 이전 버전을 지원하는 경우에도 여전히 헤더를 사용하여 -Android 3.0 이상에서 창 두 개짜리 레이아웃을 제공하도록 할 수 있습니다. 개발자가 해야 할 일은 추가로 기본 설정 XML 파일을 +

    애플리케이션이 Android 3.0 이전 버전을 지원하는 경우에도 여전히 헤더를 사용하여 +Android 3.0 이상에서 창 두 개짜리 레이아웃을 제공하도록 할 수 있습니다. 개발자가 해야 할 일은 추가로 기본 설정 XML 파일을 생성하는 것뿐입니다. 이 파일은 마치 헤더 항목처럼 동작하는 기본적인 {@link android.preference.Preference -<Preference>} 요소를 사용합니다(이것을 이전 Android 버전이 사용하도록 +<Preference>} 요소를 사용합니다(이것을 이전 Android 버전이 사용하도록 할 예정).

    하지만 새로운 {@link android.preference.PreferenceScreen}을 여는 대신 각 {@link -android.preference.Preference <Preference>} 요소가 {@link android.content.Intent}를 하나씩 -{@link android.preference.PreferenceActivity}에 전송합니다. 이것이 로딩할 XML 파일이 무엇인지를 +android.preference.Preference <Preference>} 요소가 {@link android.content.Intent}를 하나씩 +{@link android.preference.PreferenceActivity}에 전송합니다. 이것이 로딩할 XML 파일이 무엇인지를 나타냅니다.

    -

    예를 들어 다음은 Android 3.0 이상에서 사용되는 기본 설정 헤더에 대한 -XML 파일입니다({@code res/xml/preference_headers.xml}).

    +

    예를 들어 다음은 Android 3.0 이상에서 사용되는 기본 설정 헤더에 대한 +XML 파일입니다({@code res/xml/preference_headers.xml}).

     <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
    -    <header 
    +    <header
             android:fragment="com.example.prefs.SettingsFragmentOne"
             android:title="@string/prefs_category_one"
             android:summary="@string/prefs_summ_category_one" />
    -    <header 
    +    <header
             android:fragment="com.example.prefs.SettingsFragmentTwo"
             android:title="@string/prefs_category_two"
             android:summary="@string/prefs_summ_category_two" />
     </preference-headers>
     
    -

    그리고 다음은, Android 3.0 이전 버전에 같은 헤더를 제공하는 기본 설정 +

    그리고 다음은, Android 3.0 이전 버전에 같은 헤더를 제공하는 기본 설정 파일입니다({@code res/xml/preference_headers_legacy.xml}).

     <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    -    <Preference 
    +    <Preference
             android:title="@string/prefs_category_one"
             android:summary="@string/prefs_summ_category_one"  >
    -        <intent 
    +        <intent
                 android:targetPackage="com.example.prefs"
                 android:targetClass="com.example.prefs.SettingsActivity"
                 android:action="com.example.prefs.PREFS_ONE" />
         </Preference>
    -    <Preference 
    +    <Preference
             android:title="@string/prefs_category_two"
             android:summary="@string/prefs_summ_category_two" >
    -        <intent 
    +        <intent
                 android:targetPackage="com.example.prefs"
                 android:targetClass="com.example.prefs.SettingsActivity"
                 android:action="com.example.prefs.PREFS_TWO" />
    @@ -711,13 +711,13 @@ XML 파일입니다({@code res/xml/preference_headers.xml}).

    </PreferenceScreen>
    -

    {@code <preference-headers>}에 대한 지원이 Android 3.0에서 추가되었기 때문에 시스템이 +

    {@code <preference-headers>}에 대한 지원이 Android 3.0에서 추가되었기 때문에 시스템이 {@link android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()}를 {@link -android.preference.PreferenceActivity}에서 호출하는 것은 Android 3.0 이상에서 실행될 때뿐입니다. "레거시" 헤더 파일을 -로딩하려면({@code preference_headers_legacy.xml}) 반드시 Android +android.preference.PreferenceActivity}에서 호출하는 것은 Android 3.0 이상에서 실행될 때뿐입니다. "레거시" 헤더 파일을 +로딩하려면({@code preference_headers_legacy.xml}) 반드시 Android 버전을 확인해야 하며, 해당 버전이 Android 3.0 이전인 경우({@link android.os.Build.VERSION_CODES#HONEYCOMB}), {@link -android.preference.PreferenceActivity#addPreferencesFromResource addPreferencesFromResource()}를 호출하여 +android.preference.PreferenceActivity#addPreferencesFromResource addPreferencesFromResource()}를 호출하여 레거시 헤더 파일을 로딩해야 합니다. 예:

    @@ -739,8 +739,8 @@ public void onBuildHeaders(List<Header> target) {
     }
     
    -

    이제 남은 할 일이라고는 {@link android.content.Intent}를 처리하는 것뿐입니다. 이것은 -액티비티로 전달되어 어느 기본 설정 파일을 로딩해야 하는지 식별하는 데 쓰입니다. 그럼 이제 인텐트의 작업을 검색하여 기본 설정 XML의 +

    이제 남은 할 일이라고는 {@link android.content.Intent}를 처리하는 것뿐입니다. 이것은 +액티비티로 전달되어 어느 기본 설정 파일을 로딩해야 하는지 식별하는 데 쓰입니다. 그럼 이제 인텐트의 작업을 검색하여 기본 설정 XML의 {@code <intent>} 태그에서 사용한 알려진 작업 문자열에 비교해보겠습니다.

    @@ -765,8 +765,8 @@ public void onCreate(Bundle savedInstanceState) {
     

    {@link -android.preference.PreferenceActivity#addPreferencesFromResource addPreferencesFromResource()}를 연이어 호출하면 -모든 기본 설정을 하나의 목록에 쌓게 된다는 점을 유의하십시오. 따라서 이것은 'Else-if' 문이 있는 조건을 변경하여 딱 한 번만 +android.preference.PreferenceActivity#addPreferencesFromResource addPreferencesFromResource()}를 연이어 호출하면 +모든 기본 설정을 하나의 목록에 쌓게 된다는 점을 유의하십시오. 따라서 이것은 'Else-if' 문이 있는 조건을 변경하여 딱 한 번만 호출하도록 주의해야 합니다.

    @@ -775,15 +775,15 @@ android.preference.PreferenceActivity#addPreferencesFromResource addPreferencesF

    기본 설정 읽기

    -

    기본적으로 앱의 기본 설정은 모두 +

    기본적으로 앱의 기본 설정은 모두 애플리케이션 내의 어디서든 정적 메서드 {@link android.preference.PreferenceManager#getDefaultSharedPreferences PreferenceManager.getDefaultSharedPreferences()}를 호출하면 액세스할 수 있는 파일에 저장됩니다. 이것은 {@link android.content.SharedPreferences} 객체를 반환하며, 여기에 {@link -android.preference.PreferenceActivity}에서 사용한 {@link android.preference.Preference} 객체와 +android.preference.PreferenceActivity}에서 사용한 {@link android.preference.Preference} 객체와 연관된 모든 키-값 쌍이 들어있습니다.

    -

    예를 들어 다음은 기본 설정 값 중 하나를 애플리케이션 내의 다른 모든 액티비티에서 읽는 방법을 +

    예를 들어 다음은 기본 설정 값 중 하나를 애플리케이션 내의 다른 모든 액티비티에서 읽는 방법을 나타낸 것입니다.

    @@ -795,17 +795,17 @@ String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN,
     
     

    기본 설정 변경 수신 대기

    -

    사용자가 기본 설정 중 하나를 변경하자마자 이에 대해 알림을 받는 것이 좋은 데에는 몇 가지 -이유가 있습니다. 기본 설정 중 어느 하나에라도 변경이 발생했을 때 콜백을 받으려면, +

    사용자가 기본 설정 중 하나를 변경하자마자 이에 대해 알림을 받는 것이 좋은 데에는 몇 가지 +이유가 있습니다. 기본 설정 중 어느 하나에라도 변경이 발생했을 때 콜백을 받으려면, {@link android.content.SharedPreferences.OnSharedPreferenceChangeListener -SharedPreference.OnSharedPreferenceChangeListener} 인터페이스를 구현하고 +SharedPreference.OnSharedPreferenceChangeListener} 인터페이스를 구현하고 {@link android.content.SharedPreferences} 객체에 대한 수신기를 등록합니다. 이때 {@link android.content.SharedPreferences#registerOnSharedPreferenceChangeListener registerOnSharedPreferenceChangeListener()}를 호출하면 됩니다.

    이 인터페이스에는 콜백 메서드가 {@link android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged -onSharedPreferenceChanged()} 하나뿐이며, 인터페이스를 액티비티의 일부분으로 구현하는 것이 +onSharedPreferenceChanged()} 하나뿐이며, 인터페이스를 액티비티의 일부분으로 구현하는 것이 가장 쉬운 방법일 공산이 큽니다. 예:

    @@ -825,19 +825,19 @@ public class SettingsActivity extends PreferenceActivity
     }
     
    -

    이 예시에서 메서드는 변경된 설정이 알려진 기본 설정 키에 대한 것인지 여부를 확인합니다. 이것은 -{@link android.preference.PreferenceActivity#findPreference findPreference()}를 호출하여 -변경된 {@link android.preference.Preference} 객체를 가져오는데, 이렇게 해야 항목의 요약을 수정하여 +

    이 예시에서 메서드는 변경된 설정이 알려진 기본 설정 키에 대한 것인지 여부를 확인합니다. 이것은 +{@link android.preference.PreferenceActivity#findPreference findPreference()}를 호출하여 +변경된 {@link android.preference.Preference} 객체를 가져오는데, 이렇게 해야 항목의 요약을 수정하여 사용자의 선택에 대한 설명이 되도록 할 수 있습니다. 다시 말해, 설정이 {@link android.preference.ListPreference} 또는 다른 다중 선택 설정인 경우, 설정이 변경되어 현재 상태를 표시하도록 하면 {@link -android.preference.Preference#setSummary setSummary()}를 호출해야 한다는 뜻입니다(예를 들어 +android.preference.Preference#setSummary setSummary()}를 호출해야 한다는 뜻입니다(예를 들어 그림 5에 표시된 절전 모드 설정과 같음).

    -

    참고: Android 디자인 문서의 설정 관련 내용에서 설명한 바와 같이, 사용자가 기본 설정을 변경할 때마다 -{@link android.preference.ListPreference}의 요약을 업데이트하는 것을 권장합니다. 이렇게 하여 현재 설정을 +

    참고: Android 디자인 문서의 설정 관련 내용에서 설명한 바와 같이, 사용자가 기본 설정을 변경할 때마다 +{@link android.preference.ListPreference}의 요약을 업데이트하는 것을 권장합니다. 이렇게 하여 현재 설정을 나타내는 것입니다.

    -

    액티비티에서 적절한 수명 주기 관리를 수행하려면 +

    액티비티에서 적절한 수명 주기 관리를 수행하려면 {@link android.content.SharedPreferences.OnSharedPreferenceChangeListener}를 등록하고 등록 해제하는 작업은 각각 {@link android.app.Activity#onResume} 및 {@link android.app.Activity#onPause} 콜백 중에 수행하는 것을 권장합니다.

    @@ -859,14 +859,14 @@ protected void onPause() {

    주의: {@link android.content.SharedPreferences#registerOnSharedPreferenceChangeListener -registerOnSharedPreferenceChangeListener()}를 호출하면 -현재의 경우, 기본 설정 관리자가 수신기에 대한 강력한 참조를 저장하지 않습니다. 반드시 수신기에 대한 강력한 -참조를 저장해야 합니다. 그렇지 않으면 가비지 수집의 대상이 될 가능성이 높습니다. 권장 사항으로는 -수신기를 객체의 인스턴스 데이터 안에 보관하는 것을 추천합니다. 이 객체는 +registerOnSharedPreferenceChangeListener()}를 호출하면 +현재의 경우, 기본 설정 관리자가 수신기에 대한 강력한 참조를 저장하지 않습니다. 반드시 수신기에 대한 강력한 +참조를 저장해야 합니다. 그렇지 않으면 가비지 수집의 대상이 될 가능성이 높습니다. 권장 사항으로는 +수신기를 객체의 인스턴스 데이터 안에 보관하는 것을 추천합니다. 이 객체는 수신기를 필요로 하는 기간만큼 오래 존재할 것이 확실해야 합니다.

    -

    예를 들어 다음 코드에서 발신자는 수신기에 대한 참조를 -보관하지 않습니다. 그 결과 해당 수신기가 가비지 수집의 대상이 되며 +

    예를 들어 다음 코드에서 발신자는 수신기에 대한 참조를 +보관하지 않습니다. 그 결과 해당 수신기가 가비지 수집의 대상이 되며 향후 언젠가 알 수 없는 시점에 고장을 일으키게 될 것입니다.

    @@ -879,7 +879,7 @@ prefs.registerOnSharedPreferenceChangeListener(
     });
     
    -

    대신, 수신기에 대한 참조를 수신기가 필요한 기간만큼 오래 존재할 것이 확실한 객체의 +

    대신, 수신기에 대한 참조를 수신기가 필요한 기간만큼 오래 존재할 것이 확실한 객체의 인스턴스 데이터 필드에 저장하십시오.

    @@ -895,19 +895,19 @@ prefs.registerOnSharedPreferenceChangeListener(listener);
     

    네트워크 사용량 관리하기

    -

    Android 4.0부터 시스템의 설정 애플리케이션을 사용하면 사용자가 -애플리케이션이 전경과 배경에 있는 동안 각각 얼마나 많은 네트워크 데이터를 사용하는지 알아볼 수 있게 되었습니다. 그런 다음 -사용자는 각각의 앱에 대해 배경 데이터 사용을 비활성화할 수 있습니다. 사용자가 여러분의 앱이 배경에서 -데이터에 액세스하는 기능을 비활성화하는 사태를 피하려면 데이터 연결을 효율적으로 사용하고 +

    Android 4.0부터 시스템의 설정 애플리케이션을 사용하면 사용자가 +애플리케이션이 전경과 배경에 있는 동안 각각 얼마나 많은 네트워크 데이터를 사용하는지 알아볼 수 있게 되었습니다. 그런 다음 +사용자는 각각의 앱에 대해 배경 데이터 사용을 비활성화할 수 있습니다. 사용자가 여러분의 앱이 배경에서 +데이터에 액세스하는 기능을 비활성화하는 사태를 피하려면 데이터 연결을 효율적으로 사용하고 사용자가 애플리케이션 설정을 통하여 앱의 데이터 사용량을 미세 조정할 수 있도록 허용해야 합니다.

    -

    예를 들어 사용자에게 앱의 데이터 동기화 빈도를 제어하도록 허용할 수 있습니다. 앱이 Wi-Fi에 있을 때에만 -업로드/다운로드를 수행하도록 할지 여부, 앱이 로밍 중에 데이터를 사용하도록 할지 여부 등을 이렇게 조절합니다. 사용자가 -이러한 제어 기능을 사용할 수 있게 되면 시스템 설정에서 설정한 한도에 가까워지고 -있을 때 앱의 데이터 액세스를 비활성화할 가능성이 낮아집니다. 그 대신 앱이 사용하는 데이터 양을 +

    예를 들어 사용자에게 앱의 데이터 동기화 빈도를 제어하도록 허용할 수 있습니다. 앱이 Wi-Fi에 있을 때에만 +업로드/다운로드를 수행하도록 할지 여부, 앱이 로밍 중에 데이터를 사용하도록 할지 여부 등을 이렇게 조절합니다. 사용자가 +이러한 제어 기능을 사용할 수 있게 되면 시스템 설정에서 설정한 한도에 가까워지고 +있을 때 앱의 데이터 액세스를 비활성화할 가능성이 낮아집니다. 그 대신 앱이 사용하는 데이터 양을 정밀하게 제어할 수 있기 때문입니다.

    -

    일단 필요한 기본 설정을 {@link android.preference.PreferenceActivity}에 +

    일단 필요한 기본 설정을 {@link android.preference.PreferenceActivity}에 추가하여 앱의 데이터 습관을 제어하도록 했으면, 다음으로 매니페스트 파일에 있는 {@link android.content.Intent#ACTION_MANAGE_NETWORK_USAGE}에 대한 인텐트 필터를 추가해야 합니다. 예:

    @@ -920,10 +920,10 @@ android.content.Intent#ACTION_MANAGE_NETWORK_USAGE}에 대한 인텐트 필터 </activity>
    -

    이 인텐트 필터는 이것이 애플리케이션의 데이터 사용량을 제어하는 액티비티라는 -사실을 시스템에 나타내는 역할을 합니다. 따라서, 사용자가 시스템의 설정 앱에서 여러분의 앱이 -얼마나 많은 데이터를 사용하는지 알아볼 때면 애플리케이션 설정 보기 버튼을 사용할 수 있어 -{@link android.preference.PreferenceActivity}를 시작하게 됩니다. 그러면 사용자는 +

    이 인텐트 필터는 이것이 애플리케이션의 데이터 사용량을 제어하는 액티비티라는 +사실을 시스템에 나타내는 역할을 합니다. 따라서, 사용자가 시스템의 설정 앱에서 여러분의 앱이 +얼마나 많은 데이터를 사용하는지 알아볼 때면 애플리케이션 설정 보기 버튼을 사용할 수 있어 +{@link android.preference.PreferenceActivity}를 시작하게 됩니다. 그러면 사용자는 앱이 사용할 데이터 양을 미세하게 조정할 수 있습니다.

    @@ -934,22 +934,22 @@ android.content.Intent#ACTION_MANAGE_NETWORK_USAGE}에 대한 인텐트 필터

    사용자 지정 기본 설정 구축하기

    -

    Android 프레임워크에는 다양한 {@link android.preference.Preference} 하위 클래스가 포함되어 있어 -여러 가지 설정 유형에 맞게 UI를 구축할 수 있습니다. -하지만, 기본 제공 솔루션이 없는 설정이 필요하게 되는 경우도 있습니다. 예를 들어 숫자 선택기 또는 -날짜 선택기 등이 이에 해당됩니다. 그러한 경우에는 사용자 지정 기본 설정을 만들어야 합니다. 이때 +

    Android 프레임워크에는 다양한 {@link android.preference.Preference} 하위 클래스가 포함되어 있어 +여러 가지 설정 유형에 맞게 UI를 구축할 수 있습니다. +하지만, 기본 제공 솔루션이 없는 설정이 필요하게 되는 경우도 있습니다. 예를 들어 숫자 선택기 또는 +날짜 선택기 등이 이에 해당됩니다. 그러한 경우에는 사용자 지정 기본 설정을 만들어야 합니다. 이때 {@link android.preference.Preference} 클래스 또는 다른 하위 클래스 중 하나를 확장하는 방법을 씁니다.

    -

    {@link android.preference.Preference} 클래스를 확장하는 경우, 다음과 같이 +

    {@link android.preference.Preference} 클래스를 확장하는 경우, 다음과 같이 몇 가지 중요한 해야 할 일이 있습니다.

    • 사용자가 설정을 선택하면 나타나는 사용자 인터페이스를 지정합니다.
    • 필요에 따라 설정의 값을 저장합니다.
    • -
    • {@link android.preference.Preference}가 보이게 되면 +
    • {@link android.preference.Preference}가 보이게 되면 이를 현재(또는 기본) 값으로 초기화합니다.
    • 시스템이 요청하는 경우 기본 값을 제공합니다.
    • -
    • {@link android.preference.Preference}가 나름의 UI(예: 대화)를 제공하는 경우, 상태를 +
    • {@link android.preference.Preference}가 나름의 UI(예: 대화)를 제공하는 경우, 상태를 저장하고 복원하여 수명 주기 변경을 처리할 수 있도록 합니다(예: 사용자가 화면을 돌리는 경우).
    @@ -959,27 +959,27 @@ android.content.Intent#ACTION_MANAGE_NETWORK_USAGE}에 대한 인텐트 필터

    사용자 인터페이스 지정하기

    -

    {@link android.preference.Preference} 클래스를 직접 확장하는 경우, -{@link android.preference.Preference#onClick()}을 구현하여 사용자가 -항목을 선택할 때 일어날 동작을 정의해야 합니다. 그러나, 대부분의 사용자 지정 설정은 {@link android.preference.DialogPreference}를 확장하여 +

    {@link android.preference.Preference} 클래스를 직접 확장하는 경우, +{@link android.preference.Preference#onClick()}을 구현하여 사용자가 +항목을 선택할 때 일어날 동작을 정의해야 합니다. 그러나, 대부분의 사용자 지정 설정은 {@link android.preference.DialogPreference}를 확장하여 대화를 표시하도록 합니다. 이렇게 하면 절차가 단순해집니다. {@link android.preference.DialogPreference}를 확장하는 경우에는 클래스 생성자 중에 반드시 {@link -android.preference.DialogPreference#setDialogLayoutResource setDialogLayoutResourcs()}를 호출하여 +android.preference.DialogPreference#setDialogLayoutResource setDialogLayoutResourcs()}를 호출하여 대화에 대한 레이아웃을 지정해야 합니다.

    예를 들어 다음은 레이아웃을 선언하는 사용자 지정 {@link -android.preference.DialogPreference}와 기본 +android.preference.DialogPreference}와 기본 긍정적 및 부정적 대화 버튼에 대한 텍스트를 지정하는 생성자입니다.

     public class NumberPickerPreference extends DialogPreference {
         public NumberPickerPreference(Context context, AttributeSet attrs) {
             super(context, attrs);
    -        
    +
             setDialogLayoutResource(R.layout.numberpicker_dialog);
             setPositiveButtonText(android.R.string.ok);
             setNegativeButtonText(android.R.string.cancel);
    -        
    +
             setDialogIcon(null);
         }
         ...
    @@ -992,21 +992,21 @@ public class NumberPickerPreference extends DialogPreference {
     
     

    설정에 대한 값은 언제든 저장할 수 있습니다. {@link android.preference.Preference} 클래스의 {@code persist*()} 메서드 중 하나를 호출하기만 하면 됩니다. 예를 들어 설정의 값이 정수인 경우 {@link -android.preference.Preference#persistInt persistInt()}를, 부울을 저장하려면 +android.preference.Preference#persistInt persistInt()}를, 부울을 저장하려면 {@link android.preference.Preference#persistBoolean persistBoolean()}을 호출하십시오.

    -

    참고: 각각의 {@link android.preference.Preference}는 데이터 유형 하나씩만 -저장할 수 있으므로, 사용자 지정 +

    참고: 각각의 {@link android.preference.Preference}는 데이터 유형 하나씩만 +저장할 수 있으므로, 사용자 지정 {@link android.preference.Preference}에서 사용한 데이터 유형에 적절한 {@code persist*()} 메서드를 사용해야 합니다.

    설정을 유지하기로 선택하는 시점은 확장하는 지점이 {@link android.preference.Preference} 클래스인지에 좌우될 수 있습니다. {@link -android.preference.DialogPreference}를 확장하면 값을 유지하는 것은 대화가 긍정적인 결과로 인해 +android.preference.DialogPreference}를 확장하면 값을 유지하는 것은 대화가 긍정적인 결과로 인해 닫히는 경우만으로 국한해야 합니다(사용자가 "확인(OK)" 버튼을 선택하는 경우).

    {@link android.preference.DialogPreference}가 닫히면 시스템이 {@link -android.preference.DialogPreference#onDialogClosed onDialogClosed()} 메서드를 호출합니다. 이 메서드에는 -부울 인수가 포함되어 있어 사용자의 결과가 "긍정적"인지 아닌지를 나타냅니다. 이 값이 +android.preference.DialogPreference#onDialogClosed onDialogClosed()} 메서드를 호출합니다. 이 메서드에는 +부울 인수가 포함되어 있어 사용자의 결과가 "긍정적"인지 아닌지를 나타냅니다. 이 값이 true인 경우, 사용자가 긍정적 버튼을 선택한 것이고 새 값을 저장해야 합니다. 예:

    @@ -1020,29 +1020,29 @@ protected void onDialogClosed(boolean positiveResult) { }
    -

    이 예시에서 mNewValue는 설정의 현재 값을 보유한 클래스 -구성원입니다. {@link android.preference.Preference#persistInt persistInt()}를 호출하면 -{@link android.content.SharedPreferences} 파일에 대한 값을 저장합니다(이 +

    이 예시에서 mNewValue는 설정의 현재 값을 보유한 클래스 +구성원입니다. {@link android.preference.Preference#persistInt persistInt()}를 호출하면 +{@link android.content.SharedPreferences} 파일에 대한 값을 저장합니다(이 {@link android.preference.Preference}에 대하여 XML 파일에 지정된 키를 자동으로 사용합니다).

    현재 값 초기화하기

    -

    시스템이 {@link android.preference.Preference}를 화면에 추가하는 경우, 이는 -{@link android.preference.Preference#onSetInitialValue onSetInitialValue()}를 호출하여 -설정에 유지된 값이 있는지 없는지를 알립니다. 유지된 값이 없는 경우, 이 호출은 기본 값을 +

    시스템이 {@link android.preference.Preference}를 화면에 추가하는 경우, 이는 +{@link android.preference.Preference#onSetInitialValue onSetInitialValue()}를 호출하여 +설정에 유지된 값이 있는지 없는지를 알립니다. 유지된 값이 없는 경우, 이 호출은 기본 값을 제공합니다.

    -

    {@link android.preference.Preference#onSetInitialValue onSetInitialValue()} 메서드는 -부울 값 restorePersistedValue를 전달하여 해당 설정에 대해 이미 어떤 값이 유지되었는지 -아닌지를 나타냅니다. 만일 이것이 true라면, 유지된 값을 검색하되 +

    {@link android.preference.Preference#onSetInitialValue onSetInitialValue()} 메서드는 +부울 값 restorePersistedValue를 전달하여 해당 설정에 대해 이미 어떤 값이 유지되었는지 +아닌지를 나타냅니다. 만일 이것이 true라면, 유지된 값을 검색하되 {@link android.preference.Preference} 클래스의 {@code getPersisted*()} 메서드 중 하나를 호출하는 방법을 써야 합니다. 예를 들어 정수 값이라면 {@link -android.preference.Preference#getPersistedInt getPersistedInt()}를 사용합니다. 보통은 -유지된 값을 검색하여, UI에 이전에 저장된 값을 반영하여 이를 적절하게 업데이트할 수 +android.preference.Preference#getPersistedInt getPersistedInt()}를 사용합니다. 보통은 +유지된 값을 검색하여, UI에 이전에 저장된 값을 반영하여 이를 적절하게 업데이트할 수 있도록 하는 것이 좋습니다.

    -

    restorePersistedValuefalse인 경우, +

    restorePersistedValuefalse인 경우, 두 번째 인수로 전달된 기본 값을 사용해야 합니다.

    @@ -1059,22 +1059,22 @@ protected void onSetInitialValue(boolean restorePersistedValue, Object defaultVa
     }
     
    -

    각 {@code getPersisted*()} 메서드는 기본 값을 나타내는 인수를 취하여 -사실은 유지된 값이 전혀 없거나 키 자체가 존재하지 않는 경우 사용하도록 합니다. 위의 +

    각 {@code getPersisted*()} 메서드는 기본 값을 나타내는 인수를 취하여 +사실은 유지된 값이 전혀 없거나 키 자체가 존재하지 않는 경우 사용하도록 합니다. 위의 예시에서는 혹시 {@link android.preference.Preference#getPersistedInt getPersistedInt()}가 유지된 값을 반환할 수 없는 경우에 사용하도록 기본 값을 나타내는 데 로컬 상수를 사용하였습니다.

    -

    주의: {@code getPersisted*()} 메서드에서는 -defaultValue를 기본 값으로 사용하면 안 됩니다. 이것의 값은 +

    주의: {@code getPersisted*()} 메서드에서는 +defaultValue를 기본 값으로 사용하면 안 됩니다. 이것의 값은 restorePersistedValuetrue이면 항상 null이기 때문입니다.

    기본 값 제공하기

    {@link android.preference.Preference} 클래스의 인스턴스가 기본 값을 나타내는 경우 -({@code android:defaultValue} 속성으로), 시스템은 +({@code android:defaultValue} 속성으로), 시스템은 값을 검색하기 위해 객체를 인스턴트화할 때 {@link android.preference.Preference#onGetDefaultValue -onGetDefaultValue()}를 호출합니다. 이 메서드를 구현해야 +onGetDefaultValue()}를 호출합니다. 이 메서드를 구현해야 시스템이 {@link android.content.SharedPreferences}에 있는 기본 값을 저장할 수 있습니다. 예:

    @@ -1085,9 +1085,9 @@ protected Object onGetDefaultValue(TypedArray a, int index) { }
    -

    이 메서드 인수가 여러분에게 필요한 모든 것을 제공합니다. 즉 속성 배열과 -{@code android:defaultValue}의 위치로, 이는 반드시 검색해야 합니다. 이 메서드를 -반드시 구현하여 속성에서 기본 값을 추출해야만 하는 이유는 값이 정의되지 않은 경우, 속성에 대한 +

    이 메서드 인수가 여러분에게 필요한 모든 것을 제공합니다. 즉 속성 배열과 +{@code android:defaultValue}의 위치로, 이는 반드시 검색해야 합니다. 이 메서드를 +반드시 구현하여 속성에서 기본 값을 추출해야만 하는 이유는 값이 정의되지 않은 경우, 속성에 대한 로컬 기본 값을 꼭 지정해야 하기 때문입니다.

    @@ -1095,25 +1095,25 @@ protected Object onGetDefaultValue(TypedArray a, int index) {

    기본 설정의 상태 저장 및 복원하기

    레이아웃에서의 {@link android.view.View}와 마찬가지로 {@link android.preference.Preference} -하위 클래스가 액티비티 또는 프래그먼트가 재시작했을 때 -그 상태를 저장하고 복원하는 역할을 맡습니다(예를 들어 사용자가 화면을 돌리는 경우 등). -{@link android.preference.Preference} 클래스의 상태를 적절하게 저장하고 복원하려면, +하위 클래스가 액티비티 또는 프래그먼트가 재시작했을 때 +그 상태를 저장하고 복원하는 역할을 맡습니다(예를 들어 사용자가 화면을 돌리는 경우 등). +{@link android.preference.Preference} 클래스의 상태를 적절하게 저장하고 복원하려면, 수명 주기 콜백 메서드 {@link android.preference.Preference#onSaveInstanceState onSaveInstanceState()} 및 {@link android.preference.Preference#onRestoreInstanceState onRestoreInstanceState()}를 구현해야 합니다.

    -

    {@link android.preference.Preference}의 상태를 정의하는 것은 -{@link android.os.Parcelable} 인터페이스를 구현하는 객체입니다. Android 프레임워크는 +

    {@link android.preference.Preference}의 상태를 정의하는 것은 +{@link android.os.Parcelable} 인터페이스를 구현하는 객체입니다. Android 프레임워크는 그러한 객체를 제공하여 상태 객체를 정의하는 데 일종의 시작 지점으로 사용하도록 하고 있습니다. 즉 {@link android.preference.Preference.BaseSavedState} 클래스가 이에 해당됩니다.

    -

    {@link android.preference.Preference} 클래스가 자신의 상태를 저장하는 방법을 정의하려면 -{@link android.preference.Preference.BaseSavedState} 클래스를 확장해야 합니다. 아주 약간의 메서드를 재정의하고 +

    {@link android.preference.Preference} 클래스가 자신의 상태를 저장하는 방법을 정의하려면 +{@link android.preference.Preference.BaseSavedState} 클래스를 확장해야 합니다. 아주 약간의 메서드를 재정의하고 {@link android.preference.Preference.BaseSavedState#CREATOR} 객체를 정의해야 합니다.

    -

    대부분의 앱에서는 다음과 같은 구현을 복사한 다음, -{@code value}를 처리하는 줄만 변경하면 됩니다. 이는 {@link android.preference.Preference} 하위 클래스가 정수보다는 데이터 +

    대부분의 앱에서는 다음과 같은 구현을 복사한 다음, +{@code value}를 처리하는 줄만 변경하면 됩니다. 이는 {@link android.preference.Preference} 하위 클래스가 정수보다는 데이터 유형을 저장하는 경우 해당됩니다.

    @@ -1154,11 +1154,11 @@ private static class SavedState extends BaseSavedState {
     }
     
    -

    위의 {@link android.preference.Preference.BaseSavedState} 구현을 앱에 -추가하고 나면(주로 {@link android.preference.Preference} 하위 클래스의 하위 클래스로), 이제 +

    위의 {@link android.preference.Preference.BaseSavedState} 구현을 앱에 +추가하고 나면(주로 {@link android.preference.Preference} 하위 클래스의 하위 클래스로), 이제 {@link android.preference.Preference#onSaveInstanceState onSaveInstanceState()} 및 {@link -android.preference.Preference#onRestoreInstanceState onRestoreInstanceState()} 메서드를 구현해야 합니다. 이것은 +android.preference.Preference#onRestoreInstanceState onRestoreInstanceState()} 메서드를 구현해야 합니다. 이것은 {@link android.preference.Preference} 하위 클래스를 위한 것입니다.

    예:

    @@ -1194,7 +1194,7 @@ protected void onRestoreInstanceState(Parcelable state) { // Cast state to custom BaseSavedState and pass to superclass SavedState myState = (SavedState) state; super.onRestoreInstanceState(myState.getSuperState()); - + // Set this Preference's widget to reflect the restored state mNumberPicker.setValue(myState.value); } diff --git a/docs/html-intl/intl/ko/guide/topics/ui/ui-events.jd b/docs/html-intl/intl/ko/guide/topics/ui/ui-events.jd index b059bd24de48a..427051c8ac24b 100644 --- a/docs/html-intl/intl/ko/guide/topics/ui/ui-events.jd +++ b/docs/html-intl/intl/ko/guide/topics/ui/ui-events.jd @@ -16,67 +16,67 @@ parent.link=index.html -

    Android에는 사용자와 애플리케이션의 상호 작용으로부터 이벤트를 가로채는 방법이 여러 가지 있습니다. -사용자 인터페이스 내의 이벤트가 관련된 경우, 이러한 방식은 이벤트를 사용자가 상호 작용하는 +

    Android에는 사용자와 애플리케이션의 상호 작용으로부터 이벤트를 가로채는 방법이 여러 가지 있습니다. +사용자 인터페이스 내의 이벤트가 관련된 경우, 이러한 방식은 이벤트를 사용자가 상호 작용하는 특정 보기 객체로부터 캡처하는 것입니다. 이에 필요한 수단은 보기 클래스가 제공합니다.

    -

    레이아웃을 작성하는 데 사용하게 되는 여러 가지 보기 클래스 안을 보면 UI 이벤트에 유용해 보이는 공개 콜백 -메서드가 여러 개 있는 것이 눈에 띕니다. 이러한 메서드는 해당 객체에서 각각의 작업이 발생할 때 Android 프레임워크가 -호출하는 것입니다. 예를 들어 보기(예: 버튼)를 하나 터치하면 -해당 객체에서 onTouchEvent() 메서드가 호출됩니다. 그러나 이것을 가로채려면 클래스를 확장하고 -메서드를 재정의해야 합니다. 다만 그런 이벤트를 처리하기 위해 모든 보기 객체를 -다 확장하는 것은 타당성이 없습니다. 이 때문에 보기 클래스에 -일련의 중첩된 인터페이스가 있고 거기에 훨씬 쉽게 정의할 수 있는 콜백에 있습니다. 이와 같은 +

    레이아웃을 작성하는 데 사용하게 되는 여러 가지 보기 클래스 안을 보면 UI 이벤트에 유용해 보이는 공개 콜백 +메서드가 여러 개 있는 것이 눈에 띕니다. 이러한 메서드는 해당 객체에서 각각의 작업이 발생할 때 Android 프레임워크가 +호출하는 것입니다. 예를 들어 보기(예: 버튼)를 하나 터치하면 +해당 객체에서 onTouchEvent() 메서드가 호출됩니다. 그러나 이것을 가로채려면 클래스를 확장하고 +메서드를 재정의해야 합니다. 다만 그런 이벤트를 처리하기 위해 모든 보기 객체를 +다 확장하는 것은 타당성이 없습니다. 이 때문에 보기 클래스에 +일련의 중첩된 인터페이스가 있고 거기에 훨씬 쉽게 정의할 수 있는 콜백에 있습니다. 이와 같은 인터페이스를 일명 이벤트 수신기라고 하는데, 이것이 UI와 사용자 상호 작용을 캡처하는 데 아주 적합합니다.

    -

    사용자 상호 작용을 수신 대기하는 데에는 이벤트 수신기를 사용하는 것이 좀 더 보편적이지만, 사용자 지정 -구성 요소를 구축하기 위해 보기 클래스를 확장하고자 하는 상황이 올 수도 있습니다. +

    사용자 상호 작용을 수신 대기하는 데에는 이벤트 수신기를 사용하는 것이 좀 더 보편적이지만, 사용자 지정 +구성 요소를 구축하기 위해 보기 클래스를 확장하고자 하는 상황이 올 수도 있습니다. 어쩌면 {@link android.widget.Button} -클래스를 확장하여 무언가 더 복잡한 것을 만들고자 할 수도 있습니다. 이런 경우, 클래스에 대한 기본 이벤트 행동을 클래스 +클래스를 확장하여 무언가 더 복잡한 것을 만들고자 할 수도 있습니다. 이런 경우, 클래스에 대한 기본 이벤트 행동을 클래스 이벤트 처리기를 사용하여 정의할 수 있습니다.

    이벤트 수신기

    -

    이벤트 수신기란 {@link android.view.View} 클래스 내에 있는 일종의 인터페이스로, 이 안에 하나의 -콜백 메서드가 들어있습니다. 이러한 메서드는 수신기가 등록된 보기가 UI 안의 항목과 사용자의 상호 작용으로 인하여 트리거되었을 때 +

    이벤트 수신기란 {@link android.view.View} 클래스 내에 있는 일종의 인터페이스로, 이 안에 하나의 +콜백 메서드가 들어있습니다. 이러한 메서드는 수신기가 등록된 보기가 UI 안의 항목과 사용자의 상호 작용으로 인하여 트리거되었을 때 Android 프레임워크가 호출하는 것입니다.

    이벤트 수신기 인터페이스에 포함된 콜백 메서드는 다음과 같습니다.

    onClick()
    -
    {@link android.view.View.OnClickListener}에서 온 것입니다. +
    {@link android.view.View.OnClickListener}에서 온 것입니다. 이것이 호출되는 것은 사용자가 항목을 터치하거나 -(터치 모드에 있을 때), 탐색 키 또는 트랙볼을 사용하여 해당 항목에 초점을 맞추고 있으면서 +(터치 모드에 있을 때), 탐색 키 또는 트랙볼을 사용하여 해당 항목에 초점을 맞추고 있으면서 적절한 "엔터" 키를 누르거나 트랙볼을 꾹 누를 때입니다.
    onLongClick()
    -
    {@link android.view.View.OnLongClickListener}에서 온 것입니다. -이것이 호출되는 것은 사용자가 항목을 길게 누르거나(터치 모드에 있을 때), -탐색 키 또는 트랙볼을 사용하여 해당 항목에 초점을 맞추고 있으면서 +
    {@link android.view.View.OnLongClickListener}에서 온 것입니다. +이것이 호출되는 것은 사용자가 항목을 길게 누르거나(터치 모드에 있을 때), +탐색 키 또는 트랙볼을 사용하여 해당 항목에 초점을 맞추고 있으면서 적절한 "엔터" 키를 누르거나 트랙볼을 꾹 누를 때입니다(일 초간).
    onFocusChange()
    -
    {@link android.view.View.OnFocusChangeListener}에서 온 것입니다. +
    {@link android.view.View.OnFocusChangeListener}에서 온 것입니다. 이것이 호출되는 것은 사용자가 탐색 키 또는 트랙볼을 사용하여 항목 쪽으로 이동하거나 항목에서 멀어질 때입니다.
    onKey()
    -
    {@link android.view.View.OnKeyListener}에서 온 것입니다. +
    {@link android.view.View.OnKeyListener}에서 온 것입니다. 이것이 호출되는 것은 사용자가 항목에 초점을 맞추고 있으면서 기기에 있는 하드웨어 키를 누르거나 키에서 손을 떼는 경우입니다.
    onTouch()
    -
    {@link android.view.View.OnTouchListener}에서 온 것입니다. -이것이 호출되는 것은 사용자가 터치 이벤트로서의 자격을 만족하는 작업을 수행하는 경우로, 여기에 +
    {@link android.view.View.OnTouchListener}에서 온 것입니다. +이것이 호출되는 것은 사용자가 터치 이벤트로서의 자격을 만족하는 작업을 수행하는 경우로, 여기에 누르기, 손 떼기와 화면에서 이루어지는 모든 움직임 동작(항목의 경계 내에서)이 포함됩니다.
    onCreateContextMenu()
    -
    {@link android.view.View.OnCreateContextMenuListener}에서 온 것입니다. -이것을 호출하는 것은 컨텍스트 메뉴가 구축되는 중일 때입니다(정체된 "롱 클릭"의 결과로). +
    {@link android.view.View.OnCreateContextMenuListener}에서 온 것입니다. +이것을 호출하는 것은 컨텍스트 메뉴가 구축되는 중일 때입니다(정체된 "롱 클릭"의 결과로). 메뉴 개발자 가이드에 있는 컨텍스트 메뉴 관련 논의를 참조하십시오.
    -

    이러한 메서드는 각자의 인터페이스 안에 거주하는 유일한 주민입니다. 이러한 메서드 중 하나를 -정의하고 이벤트를 처리하려면 액티비티 내의 중첩된 인터페이스를 구현하거나 익명의 클래스로 정의하면 됩니다. -그런 다음 구현의 인스턴스 하나를 -각각의 View.set...Listener() 메서드에 전달하십시오 (예: -{@link android.view.View#setOnClickListener(View.OnClickListener) setOnClickListener()}를 +

    이러한 메서드는 각자의 인터페이스 안에 거주하는 유일한 주민입니다. 이러한 메서드 중 하나를 +정의하고 이벤트를 처리하려면 액티비티 내의 중첩된 인터페이스를 구현하거나 익명의 클래스로 정의하면 됩니다. +그런 다음 구현의 인스턴스 하나를 +각각의 View.set...Listener() 메서드에 전달하십시오 (예: +{@link android.view.View#setOnClickListener(View.OnClickListener) setOnClickListener()}를 호출한 다음 이를 {@link android.view.View.OnClickListener OnClickListener}의 구현에 전달합니다).

    아래의 예시는 버튼에 대하여 온-클릭 수신기를 등록하는 방법을 나타낸 것입니다.

    @@ -117,57 +117,57 @@ public class ExampleActivity extends Activity implements OnClickListener { }
    -

    위의 예시에서 onClick() 콜백에는 -반환 값이 없지만 다른 이벤트 수신기 메서드 중에는 부울 값을 반환해야만 하는 것도 있다는 점을 유의하십시오. 그 이유는 이벤트에 따라 +

    위의 예시에서 onClick() 콜백에는 +반환 값이 없지만 다른 이벤트 수신기 메서드 중에는 부울 값을 반환해야만 하는 것도 있다는 점을 유의하십시오. 그 이유는 이벤트에 따라 다릅니다. 이런 필수 사항이 적용되는 몇몇 메서드의 경우, 이유는 다음과 같습니다.

      -
    • {@link android.view.View.OnLongClickListener#onLongClick(View) onLongClick()} - -이것은 부울 값을 반환하여 이벤트를 완전히 사용하였으며 더 이상 이를 담지 않아도 되는지 여부를 나타냅니다. -다시 말해, 을 반환하면 이벤트를 처리했으며 여기에서 중단해야 한다는 것을 의미하며 -거짓을 반환하면 이벤트가 아직 미처리 상태이며/거나 이 이벤트를 다른 -온-클릭 수신기로 계속 진행해야 할지 나타내는 것입니다.
    • -
    • {@link android.view.View.OnKeyListener#onKey(View,int,KeyEvent) onKey()} - +
    • {@link android.view.View.OnLongClickListener#onLongClick(View) onLongClick()} - 이것은 부울 값을 반환하여 이벤트를 완전히 사용하였으며 더 이상 이를 담지 않아도 되는지 여부를 나타냅니다. - 다시 말해, 을 반환하면 이벤트를 처리했으며 여기에서 중단해야 한다는 것을 의미하며 -거짓을 반환하면 이벤트가 아직 미처리 상태이며/거나 이 이벤트를 다른 +다시 말해, 을 반환하면 이벤트를 처리했으며 여기에서 중단해야 한다는 것을 의미하며 +거짓을 반환하면 이벤트가 아직 미처리 상태이며/거나 이 이벤트를 다른 +온-클릭 수신기로 계속 진행해야 할지 나타내는 것입니다.
    • +
    • {@link android.view.View.OnKeyListener#onKey(View,int,KeyEvent) onKey()} - +이것은 부울 값을 반환하여 이벤트를 완전히 사용하였으며 더 이상 이를 담지 않아도 되는지 여부를 나타냅니다. + 다시 말해, 을 반환하면 이벤트를 처리했으며 여기에서 중단해야 한다는 것을 의미하며 +거짓을 반환하면 이벤트가 아직 미처리 상태이며/거나 이 이벤트를 다른 온-키 수신기로 계속 진행해야 할지 나타내는 것입니다.
    • -
    • {@link android.view.View.OnTouchListener#onTouch(View,MotionEvent) onTouch()} - -이것은 부울 값을 반환하여 수신기가 이 이벤트를 사용하는지 아닌지를 나타냅니다. 여기서 중요한 점은 -이 이벤트에는 서로 연달아 발생하는 여러 개의 작업이 있을 수 있다는 것입니다. 그러므로 '아래로' 작업 이벤트를 수신했을 때 거짓을 반환하면, -해당 이벤트를 사용하지 않았으며 이 이벤트로부터 이어지는 이후의 작업에 -흥미가 없음을 나타내는 것이 됩니다. 따라서 이 이벤트 내의 다른 모든 작업에 대해 +
    • {@link android.view.View.OnTouchListener#onTouch(View,MotionEvent) onTouch()} - +이것은 부울 값을 반환하여 수신기가 이 이벤트를 사용하는지 아닌지를 나타냅니다. 여기서 중요한 점은 +이 이벤트에는 서로 연달아 발생하는 여러 개의 작업이 있을 수 있다는 것입니다. 그러므로 '아래로' 작업 이벤트를 수신했을 때 거짓을 반환하면, +해당 이벤트를 사용하지 않았으며 이 이벤트로부터 이어지는 이후의 작업에 +흥미가 없음을 나타내는 것이 됩니다. 따라서 이 이벤트 내의 다른 모든 작업에 대해 호출되지 않습니다(예: 손가락 동작 또는 최종적인 '위로' 작업 이벤트 등).
    -

    하드웨어 키 이벤트는 항상 현재 초점의 중심에 있는 보기로 전달된다는 점을 명심하십시오. 이들은 보기 계층의 맨 위에서 시작하여 -아래 방향으로 발송되어 적절한 목적지에 도달할 때까지 계속합니다. 보기(또는 보기의 하위)에 +

    하드웨어 키 이벤트는 항상 현재 초점의 중심에 있는 보기로 전달된다는 점을 명심하십시오. 이들은 보기 계층의 맨 위에서 시작하여 +아래 방향으로 발송되어 적절한 목적지에 도달할 때까지 계속합니다. 보기(또는 보기의 하위)에 현재 초점이 맞춰져 있으면, 이벤트가 {@link android.view.View#dispatchKeyEvent(KeyEvent) -dispatchKeyEvent()} 메서드를 통과하여 이동하는 것을 확인할 수 있습니다. 보기를 통해 키 이벤트를 캡처하는 대신, 액티비티 내부의 모든 이벤트를 {@link android.app.Activity#onKeyDown(int,KeyEvent) onKeyDown()}및 +dispatchKeyEvent()} 메서드를 통과하여 이동하는 것을 확인할 수 있습니다. 보기를 통해 키 이벤트를 캡처하는 대신, 액티비티 내부의 모든 이벤트를 {@link android.app.Activity#onKeyDown(int,KeyEvent) onKeyDown()}{@link android.app.Activity#onKeyUp(int,KeyEvent) onKeyUp()}을 사용하여 수신할 수도 있습니다.

    -

    또한, 애플리케이션에 대한 텍스트 입력의 경우 대다수의 기기에는 소프트웨어 입력 메서드만 있다는 사실을 -명심하십시오. 그러한 메서드는 반드시 키 기반이 아니어도 됩니다. 음성 입력, 손글씨 등을 사용하는 것도 있습니다. 입력 -메서드가 키보드 같은 인터페이스를 표시하더라도 일반적으로 -{@link android.app.Activity#onKeyDown(int,KeyEvent) onKeyDown()} 이벤트군을 트리거하지는 않습니다. 특정 키 누름을 -제어해야만 하는 UI는 절대 구축하면 안 됩니다. 이렇게 하면 애플리케이션이 하드웨어 키보드가 있는 -기기에만 한정됩니다. 특히, 사용자가 리턴 키를 누르면 입력의 유효성을 검사하는 데 이와 같은 메서드에 -의존해서는 안 됩니다. 대신, {@link android.view.inputmethod.EditorInfo#IME_ACTION_DONE}과 같은 작업을 사용하여 애플리케이션이 반응할 것으로 기대되는 방식에 해당되는 -입력 메서드를 신호하여 의미 있는 방식으로 UI를 변경할 수 있게 하는 것이 좋습니다. 소프트웨어 입력 메서드가 +

    또한, 애플리케이션에 대한 텍스트 입력의 경우 대다수의 기기에는 소프트웨어 입력 메서드만 있다는 사실을 +명심하십시오. 그러한 메서드는 반드시 키 기반이 아니어도 됩니다. 음성 입력, 손글씨 등을 사용하는 것도 있습니다. 입력 +메서드가 키보드 같은 인터페이스를 표시하더라도 일반적으로 +{@link android.app.Activity#onKeyDown(int,KeyEvent) onKeyDown()} 이벤트군을 트리거하지는 않습니다. 특정 키 누름을 +제어해야만 하는 UI는 절대 구축하면 안 됩니다. 이렇게 하면 애플리케이션이 하드웨어 키보드가 있는 +기기에만 한정됩니다. 특히, 사용자가 리턴 키를 누르면 입력의 유효성을 검사하는 데 이와 같은 메서드에 +의존해서는 안 됩니다. 대신, {@link android.view.inputmethod.EditorInfo#IME_ACTION_DONE}과 같은 작업을 사용하여 애플리케이션이 반응할 것으로 기대되는 방식에 해당되는 +입력 메서드를 신호하여 의미 있는 방식으로 UI를 변경할 수 있게 하는 것이 좋습니다. 소프트웨어 입력 메서드가 어떻게 작동할지 임의로 추정하지 마시고, 이미 서식 지정된 텍스트를 애플리케이션에 제공해줄 것이라 믿으면 됩니다.

    -

    참고: Androids는 우선 이벤트 처리기부터 호출하고, 그 다음에 클래스 정의로부터 가져온 -적절한 기본 처리기를 두 번째로 호출합니다. 따라서, 이와 같은 이벤트 수신기에서 을 반환하면 이벤트가 -다른 이벤트 수신기로 전파되는 것을 중지시킬 뿐만 아니라 보기에 있는 +

    참고: Androids는 우선 이벤트 처리기부터 호출하고, 그 다음에 클래스 정의로부터 가져온 +적절한 기본 처리기를 두 번째로 호출합니다. 따라서, 이와 같은 이벤트 수신기에서 을 반환하면 이벤트가 +다른 이벤트 수신기로 전파되는 것을 중지시킬 뿐만 아니라 보기에 있는 기본 이벤트 처리기로의 콜백도 차단하게 됩니다. 따라서 을 반환하는 경우 해당 이벤트를 종료하고 싶은 것인지 확신해야 합니다.

    이벤트 처리기

    -

    보기에서 사용자 지정 구성 요소를 구축하는 경우, 기본 이벤트 처리기로 사용될 콜백 메서드를 +

    보기에서 사용자 지정 구성 요소를 구축하는 경우, 기본 이벤트 처리기로 사용될 콜백 메서드를 여러 개 정의할 수 있게 됩니다. 사용자 지정 -구성 요소에 대한 문서를 보면 이벤트 처리에 사용되는 몇 가지 보편적인 콜백을 확인할 수 있습니다. +구성 요소에 대한 문서를 보면 이벤트 처리에 사용되는 몇 가지 보편적인 콜백을 확인할 수 있습니다. 다음은 그 몇 가지 예입니다.

    • {@link android.view.View#onKeyDown} - 새로운 키 이벤트가 발생하면 호출합니다.
    • @@ -176,68 +176,68 @@ dispatchKeyEvent()} 메서드를 통과하여 이동하는 것을 확인
    • {@link android.view.View#onTouchEvent} - 터치 스크린 동작 이벤트가 발생하면 호출합니다.
    • {@link android.view.View#onFocusChanged} - 보기가 초점을 취하거나 이를 잃으면 호출합니다.
    -

    개발자 여러분이 알아두어야 하는 다른 메서드가 몇 가지 더 있습니다. 이들은 보기 클래스의 일부분이 아니지만, -이벤트를 처리할 수 있는 방식에 직접적으로 영향을 미칠 수 있는 것들입니다. 그러니, 레이아웃 안에서 좀 더 복잡한 이벤트를 관리하는 경우, +

    개발자 여러분이 알아두어야 하는 다른 메서드가 몇 가지 더 있습니다. 이들은 보기 클래스의 일부분이 아니지만, +이벤트를 처리할 수 있는 방식에 직접적으로 영향을 미칠 수 있는 것들입니다. 그러니, 레이아웃 안에서 좀 더 복잡한 이벤트를 관리하는 경우, 이와 같은 다른 메서드도 고려하십시오.

    • {@link android.app.Activity#dispatchTouchEvent(MotionEvent) - Activity.dispatchTouchEvent(MotionEvent)} - 이것을 사용하면 {@link + Activity.dispatchTouchEvent(MotionEvent)} - 이것을 사용하면 {@link android.app.Activity}로 하여금 모든 터치 이벤트가 창으로 발송되기 전에 이들을 가로채도록 할 수 있습니다.
    • {@link android.view.ViewGroup#onInterceptTouchEvent(MotionEvent) ViewGroup.onInterceptTouchEvent(MotionEvent)} - 이것을 사용하면 {@link android.view.ViewGroup}으로 하여금 이벤트가 하위 보기로 발송되는 것을 지켜보도록 할 수 있습니다.
    • {@link android.view.ViewParent#requestDisallowInterceptTouchEvent(boolean) - ViewParent.requestDisallowInterceptTouchEvent(boolean)} - 이것을 -호출하는 것은 상위 보기에 {@link + ViewParent.requestDisallowInterceptTouchEvent(boolean)} - 이것을 +호출하는 것은 상위 보기에 {@link android.view.ViewGroup#onInterceptTouchEvent(MotionEvent)}가 있는 터치 이벤트를 가로채면 안 된다고 나타낼 때입니다.

    터치 모드

    -사용자가 방향 키 또는 트랙볼을 사용하여 사용자 인터페이스를 탐색하고 있는 경우, -조치 가능한 항목(예: 버튼)에 초점을 맞춰 어느 것이 입력을 허용할지 사용자가 -볼 수 있도록 해야 합니다. 하지만 기기에 터치 기능이 있고 사용자가 -인터페이스를 터치하여 인터페이스와의 상호 작용을 시작하는 경우라면, 더 이상 항목을 강조 표시하거나 -특정 보기에 초점을 맞추지 않아도 됩니다. 따라서 "터치 모드"라고 불리는 상호 작용에 대한 -모드가 따로 있습니다. +사용자가 방향 키 또는 트랙볼을 사용하여 사용자 인터페이스를 탐색하고 있는 경우, +조치 가능한 항목(예: 버튼)에 초점을 맞춰 어느 것이 입력을 허용할지 사용자가 +볼 수 있도록 해야 합니다. 하지만 기기에 터치 기능이 있고 사용자가 +인터페이스를 터치하여 인터페이스와의 상호 작용을 시작하는 경우라면, 더 이상 항목을 강조 표시하거나 +특정 보기에 초점을 맞추지 않아도 됩니다. 따라서 "터치 모드"라고 불리는 상호 작용에 대한 +모드가 따로 있습니다.

    -터치 기능이 있는 기기의 경우, 사용자가 화면을 터치하면 기기가 터치 모드에 -진입하게 됩니다. 이 시점부터는 -{@link android.view.View#isFocusableInTouchMode}가 참인 보기에만 초점을 맞출 수 있습니다. 예를 들어 텍스트 편집 위젯이 이에 해당됩니다. -버튼처럼 터치할 수 있는 다른 보기의 경우 터치해도 주의를 끌 수 없으며 이를 누르면 그저 +터치 기능이 있는 기기의 경우, 사용자가 화면을 터치하면 기기가 터치 모드에 +진입하게 됩니다. 이 시점부터는 +{@link android.view.View#isFocusableInTouchMode}가 참인 보기에만 초점을 맞출 수 있습니다. 예를 들어 텍스트 편집 위젯이 이에 해당됩니다. +버튼처럼 터치할 수 있는 다른 보기의 경우 터치해도 주의를 끌 수 없으며 이를 누르면 그저 온-클릭 수신기를 실행시키기만 합니다.

    -사용자가 방향 키를 누르거나 트랙볼로 스크롤 동작을 할 때마다 기기가 -터치 모드를 종료하고 초점을 맞출 보기를 찾습니다. 이제 사용자는 사용자 인터페이스와 +사용자가 방향 키를 누르거나 트랙볼로 스크롤 동작을 할 때마다 기기가 +터치 모드를 종료하고 초점을 맞출 보기를 찾습니다. 이제 사용자는 사용자 인터페이스와 상호 작용을 재개해도 되며, 화면을 터치하지 않아도 됩니다.

    -터치 모드 상태는 시스템 전체를 통틀어 유지됩니다(모든 창과 액티비티 포함). -현재 상태를 쿼리하려면 +터치 모드 상태는 시스템 전체를 통틀어 유지됩니다(모든 창과 액티비티 포함). +현재 상태를 쿼리하려면 {@link android.view.View#isInTouchMode}를 호출하여 기기가 현재 터치 모드에 있는지 확인하면 됩니다.

    초점 처리하기

    -

    프레임워크가 사용자 입력에 응답하여 일상적인 초점 이동을 처리합니다. -여기에는 보기가 제거되거나 숨겨지는 것, 또는 새 보기를 사용할 수 있게 됨에 따라 -초점을 변경하는 것이 포함됩니다. 보기는 초점을 취하고자 하는 의향을 -{@link android.view.View#isFocusable()} 메서드를 통해 나타냅니다. 보기가 초점을 취할 수 있는지 여부를 변경하려면 -{@link android.view.View#setFocusable(boolean) setFocusable()}을 호출합니다. 터치 모드에 있는 경우, -어느 보기가 {@link android.view.View#isFocusableInTouchMode()}로 초점을 취하는 것을 허용하는지 여부를 쿼리할 수 있습니다. +

    프레임워크가 사용자 입력에 응답하여 일상적인 초점 이동을 처리합니다. +여기에는 보기가 제거되거나 숨겨지는 것, 또는 새 보기를 사용할 수 있게 됨에 따라 +초점을 변경하는 것이 포함됩니다. 보기는 초점을 취하고자 하는 의향을 +{@link android.view.View#isFocusable()} 메서드를 통해 나타냅니다. 보기가 초점을 취할 수 있는지 여부를 변경하려면 +{@link android.view.View#setFocusable(boolean) setFocusable()}을 호출합니다. 터치 모드에 있는 경우, +어느 보기가 {@link android.view.View#isFocusableInTouchMode()}로 초점을 취하는 것을 허용하는지 여부를 쿼리할 수 있습니다. 이것은 {@link android.view.View#setFocusableInTouchMode(boolean) setFocusableInTouchMode()}로 변경하면 됩니다.

    -

    초점 이동은 주어진 방향에서 가장 가까운 이웃을 찾아내는 알고리즘을 기반으로 -합니다. 드문 일이지만 기본 알고리즘이 개발자가 의도한 행동과 일치하지 않는 -경우도 있습니다. 이러한 상황이라면, 레이아웃 파일에서 다음과 같은 XML 속성을 +

    초점 이동은 주어진 방향에서 가장 가까운 이웃을 찾아내는 알고리즘을 기반으로 +합니다. 드문 일이지만 기본 알고리즘이 개발자가 의도한 행동과 일치하지 않는 +경우도 있습니다. 이러한 상황이라면, 레이아웃 파일에서 다음과 같은 XML 속성을 사용하여 명시적 재정의를 제공하면 됩니다. nextFocusDown, nextFocusLeft, nextFocusRight, 및 -nextFocusUp입니다. 이와 같은 속성 중 한 가지를 초점이 떠나고 있는 보기에 -추가합니다. 속성의 값을 초점을 +nextFocusUp입니다. 이와 같은 속성 중 한 가지를 초점이 떠나고 있는 보기에 +추가합니다. 속성의 값을 초점을 맞춰야 할 보기의 ID가 되도록 정의합니다. 예:

     <LinearLayout
    @@ -252,18 +252,18 @@ dispatchKeyEvent()} 메서드를 통과하여 이동하는 것을 확인
     </LinearLayout>
     
    -

    보통은 이런 수직 레이아웃에서 첫 버튼부터 위로 이동하면 아무 데도 갈 수 없고, -두 번째 버튼에서 아래로 이동해도 마찬가지입니다. 이제 맨 위 버튼이 맨 아래 버튼을 다음과 같이 -정의했습니다. nextFocusUp (반대쪽도 마찬가지) 따라서 이동 초점은 위에서 아래로 갔다가 +

    보통은 이런 수직 레이아웃에서 첫 버튼부터 위로 이동하면 아무 데도 갈 수 없고, +두 번째 버튼에서 아래로 이동해도 마찬가지입니다. 이제 맨 위 버튼이 맨 아래 버튼을 다음과 같이 +정의했습니다. nextFocusUp (반대쪽도 마찬가지) 따라서 이동 초점은 위에서 아래로 갔다가 아래에서 위로 순환하게 됩니다.

    -

    보기를 UI에서 초점을 맞출 수 있는 것으로 선언하고자 하는 경우(일반적으로는 그렇지 않음), -보기에 레이아웃 선언에서 android:focusable XML 속성을 추가합니다. -이 값을 으로 설정합니다. 터치 모드에 있을 때에도 보기를 초점을 맞출 수 있는 것으로 +

    보기를 UI에서 초점을 맞출 수 있는 것으로 선언하고자 하는 경우(일반적으로는 그렇지 않음), +보기에 레이아웃 선언에서 android:focusable XML 속성을 추가합니다. +이 값을 으로 설정합니다. 터치 모드에 있을 때에도 보기를 초점을 맞출 수 있는 것으로 선언할 수 있습니다. android:focusableInTouchMode를 사용하면 됩니다.

    특정 보기에 초점을 맞추기를 요청하려면, {@link android.view.View#requestFocus()}를 호출하십시오.

    -

    초점 이벤트를 수신 대기하려면(어떤 보기에 초점이 맞춰지거나 이를 잃는 경우 알림을 받으려면), -{@link android.view.View.OnFocusChangeListener#onFocusChange(View,boolean) onFocusChange()}를 사용하면 됩니다. +

    초점 이벤트를 수신 대기하려면(어떤 보기에 초점이 맞춰지거나 이를 잃는 경우 알림을 받으려면), +{@link android.view.View.OnFocusChangeListener#onFocusChange(View,boolean) onFocusChange()}를 사용하면 됩니다. 이는 위의 이벤트 수신기 섹션에서 이야기한 바와 같습니다.

    @@ -282,7 +282,7 @@ dispatchKeyEvent()} 메서드를 통과하여 이동하는 것을 확인 the framework will take care of measuring, laying out, and drawing the tree as appropriate. - +

    Note: The entire View tree is single threaded. You must always be on the UI thread when calling any method on any View. If you are doing work on other threads and want to update the state of a View diff --git a/docs/html-intl/intl/ko/preview/api-overview.jd b/docs/html-intl/intl/ko/preview/api-overview.jd index fdae40619bd14..5cffdfb235727 100644 --- a/docs/html-intl/intl/ko/preview/api-overview.jd +++ b/docs/html-intl/intl/ko/preview/api-overview.jd @@ -311,7 +311,7 @@ Data Saver 기본 설정을 검색하고 Vulkan API

    - Android N은 새로운 3D 렌더링 API인 Vulkan™을 플랫폼에 통합합니다. + Android N은 새로운 3D 렌더링 API인 Vulkan™을 플랫폼에 통합합니다. OpenGL™ ES와 마찬가지로, Vulkan은 Khronos Group에 의해 관리되는 3D 그래픽 및 렌더링을 위한 공개 표준입니다. @@ -502,7 +502,7 @@ API를 사용하여 사용자의 로케일을 가져온 이모티콘에 대한 시각적 표시를 제공해야 하며, 사용자가 선호하는 피부 색조를 선택하도록 허용해야 합니다. 어떤 시스템 이모티콘에 피부 색조 한정자가 있는지 확인하려면 {@link android.graphics.Paint#hasGlyph(String)} -메서드를 사용하세요. +메서드를 사용하세요. 유니코드 설명서를 읽어보면 어떤 이모티콘에서 피부 색조가 사용되는지 확인할 수 있습니다. @@ -857,7 +857,7 @@ Android N에서는 사용자가 "Alt + /" 키를 눌러 Keyboard Shortcuts diff --git a/docs/html-intl/intl/ko/preview/behavior-changes.jd b/docs/html-intl/intl/ko/preview/behavior-changes.jd index 709ccfc2f0793..5d325e1b41dbe 100644 --- a/docs/html-intl/intl/ko/preview/behavior-changes.jd +++ b/docs/html-intl/intl/ko/preview/behavior-changes.jd @@ -167,7 +167,7 @@ CPU 및 네트워크 제한의 하위 세트를 적용하여 잠자기 모드를 Android N 기기를 올바로 대상으로 삼을 수 있도록 이들 인텐트에 대한 종속성을 최대한 빨리 제거해야 합니다. Android 프레임워크는 이러한 암시적 브로드캐스트의 필요성을 줄이기 위한 여러 가지 해결책을 제공합니다. 예를 들어, {@link - android.app.job.JobScheduler} API는 지정된 조건(예: + android.app.job.JobScheduler} API는 지정된 조건(예: 고정 요금제 네트워크에 연결)이 충족될 경우 네트워크 운영을 예약할 수 있는 강력한 메커니즘을 제공합니다. 심지어 {@link android.app.job.JobScheduler}를 사용하여 콘텐츠 공급자의 변경 사항에 대응할 수도 있습니다. @@ -224,7 +224,7 @@ API 또는 {@link java.io.File File} API를 사용하여 개인 디렉터리에 대상으로 하는 앱은 {@link android.app.DownloadManager#COLUMN_LOCAL_FILENAME}에 액세스할 때 {@link java.lang.SecurityException}을 트리거합니다. - + {@link android.app.DownloadManager.Request#setDestinationInExternalFilesDir DownloadManager.Request.setDestinationInExternalFilesDir()} 또는 @@ -562,7 +562,7 @@ TCP 소켓에 대한 쓰기를 엄격 모드 위반으로서 플래그하지 못

  • -{@code Debug.startMethodTracing()} 계열에 속하는 메서드는, +{@code Debug.startMethodTracing()} 계열에 속하는 메서드는, SD 카드의 최상위 레벨에 저장하는 것이 아니라, 이제 공유 저장소의 패키지별 디렉터리에 출력을 기본적으로 저장합니다. 즉, 앱은 이들 API를 사용하기 위해 {@code WRITE_EXTERNAL_STORAGE} 권한을 요청할 필요가 더 이상 없습니다. diff --git a/docs/html-intl/intl/ko/preview/features/direct-boot.jd b/docs/html-intl/intl/ko/preview/features/direct-boot.jd index 981c3e0808989..2674481181a48 100644 --- a/docs/html-intl/intl/ko/preview/features/direct-boot.jd +++ b/docs/html-intl/intl/ko/preview/features/direct-boot.jd @@ -18,7 +18,7 @@ page.image=images/cards/card-nyc_2x.jpg -

    기기에 전원이 들어와 있지만 사용자가 기기의 잠금을 해제하지 않았을 경우 Android N은 안전한 +

    기기에 전원이 들어와 있지만 사용자가 기기의 잠금을 해제하지 않았을 경우 Android N은 안전한 직접 부팅 모드에서 실행됩니다. 이를 지원하기 위해 시스템에서 다음과 같은 두 가지 데이터 저장소 위치를 제공합니다.

    @@ -125,7 +125,7 @@ ACTION_BOOT_COMPLETED} 메시지를 수신할 수 있습니다. 이 메시지는

    기존 데이터 마이그레이션

    직접 부팅 모드를 사용하도록 사용자가 자신의 기기를 업데이트하는 경우, -여러분이 기존 데이터를 기기 암호화 저장소로 마이그레이션해야 할 수도 있습니다. +여러분이 기존 데이터를 기기 암호화 저장소로 마이그레이션해야 할 수도 있습니다. Context.moveSharedPreferencesFrom()Context.moveDatabaseFrom()을 사용하여 자격 증명 암호화 저장소와 기기 암호화 저장소 간에 기본 설정과 데이터베이스 데이터를 마이그레이션합니다.

    diff --git a/docs/html-intl/intl/ko/preview/features/icu4j-framework.jd b/docs/html-intl/intl/ko/preview/features/icu4j-framework.jd index f626bff6bde95..921873d8e6f21 100644 --- a/docs/html-intl/intl/ko/preview/features/icu4j-framework.jd +++ b/docs/html-intl/intl/ko/preview/features/icu4j-framework.jd @@ -50,7 +50,7 @@ Android 프레임워크에서 ICU4J API를 사용하는 방법을 설명합니

    Android N은 -com.ibm.icu가 아니라 android.icu 패키지를 통해 ICU4J API의 하위 세트를 노출합니다. +com.ibm.icu가 아니라 android.icu 패키지를 통해 ICU4J API의 하위 세트를 노출합니다. Android 프레임워크는 여러 가지 이유로 ICU4J API를 노출하지 않을 수 있습니다. 예컨대 Android N은 일부 사용 중단된 API나 ICU 팀에서 안정적이라고 선언하지 않은 API를 diff --git a/docs/html-intl/intl/ko/preview/features/tv-recording-api.jd b/docs/html-intl/intl/ko/preview/features/tv-recording-api.jd index f353cc6a4e677..fa557bcf14fdd 100644 --- a/docs/html-intl/intl/ko/preview/features/tv-recording-api.jd +++ b/docs/html-intl/intl/ko/preview/features/tv-recording-api.jd @@ -81,7 +81,7 @@ page.image=images/cards/card-nyc_2x.jpg 전송하는 역할을 담당합니다.

    시스템이 RecordingSession.onTune()을 호출하면 -채널 URI에 전달되고, URI가 지정하는 채널에 맞춰 조정됩니다. +채널 URI에 전달되고, URI가 지정하는 채널에 맞춰 조정됩니다. notifyTuned()를 호출해서 앱이 원하는 채널에 맞춰졌음을 시스템에 알리거나 앱이 적절한 채널에 맞출 수 없으면 notifyError()를 호출합니다.

    diff --git a/docs/html-intl/intl/ko/preview/setup-sdk.jd b/docs/html-intl/intl/ko/preview/setup-sdk.jd index 03727a3320dbe..c2a0380de61ca 100644 --- a/docs/html-intl/intl/ko/preview/setup-sdk.jd +++ b/docs/html-intl/intl/ko/preview/setup-sdk.jd @@ -92,7 +92,7 @@ Platform-Tools, Android SDK Tools 체크박스를 n-preview-3-docs.zip
  • 무선 버튼 확인란과 비슷하지만, 예외가 있다면 그룹 내에서 하나만 선택할 수 있다는 점입니다.{@link android.widget.RadioGroup RadioGroup} + {@link android.widget.RadioGroup RadioGroup}
    {@link android.widget.RadioButton RadioButton}
    MD5: 19bcfd057a1f9dd01ffbb3d8ff7b8d81
    - SHA-1: 9224bd4445cd7f653c4c294d362ccb195a2101e7 + SHA-1: 9224bd4445cd7f653c4c294d362ccb195a2101e7
    diff --git a/docs/html-intl/intl/ko/training/basics/activity-lifecycle/index.jd b/docs/html-intl/intl/ko/training/basics/activity-lifecycle/index.jd index e66e8d19c372e..4fd4af25afd43 100644 --- a/docs/html-intl/intl/ko/training/basics/activity-lifecycle/index.jd +++ b/docs/html-intl/intl/ko/training/basics/activity-lifecycle/index.jd @@ -35,11 +35,11 @@ startpage=true

    사용자가 앱을 탐색하고, 앱에서 나가고, 앱으로 다시 돌아가면, 앱의 -{@link android.app.Activity} 인스턴스는 +{@link android.app.Activity} 인스턴스는 수명 주기 안에서 서로 다른 상태 간에 전환됩니다. 예를 들어 액티비티가 처음 시작되는 경우, 시스템의 전면에 표시되어 사용자의 포커스를 받습니다. 이 과정에서 Android 시스템은 사용자 인터페이스 및 다른 구성요소에 설정된 -액티비티에 대해 일련의 수명 주기 메서드를 호출합니다. 사용자가 다른 액티비티를 시작하거나 다른 앱으로 전환하는 +액티비티에 대해 일련의 수명 주기 메서드를 호출합니다. 사용자가 다른 액티비티를 시작하거나 다른 앱으로 전환하는 작업을 수행하면, 백그라운드(액티비티가 더 이상 보이지 않지만 인스턴스와 해당 상태는 그대로 유지되는 상태)로 전환되면서 시스템은 액티비티에 대해 또 다른 수명 주기 메서드 세트를 호출합니다.

    @@ -55,7 +55,7 @@ android.app.Activity} 인스턴스가 수신하는 중요한 수명 주기 콜 사용자가 원하는 작업을 하고, 액티비티가 필요로 하지 않을 때 시스템 리소스 소비를 방지하는 방법에 대해서도 설명합니다.

    과정

    - +
    액티비티 시작하기
    액티비티 수명 주기의 기본사항, 사용자가 앱을 시작하는 방법, 그리고 기본 액티비티 생성 작업을 수행하는 @@ -68,5 +68,5 @@ android.app.Activity} 인스턴스가 수신하는 중요한 수명 주기 콜
    액티비티 재생성하기
    액티비티가 소멸되면 어떤 동작이 발생하는지, 그리고 필요 시 액티비티 상태를 재구축하는 방법에 대해 설명합니다.
    -
    + diff --git a/docs/html-intl/intl/ko/training/basics/activity-lifecycle/pausing.jd b/docs/html-intl/intl/ko/training/basics/activity-lifecycle/pausing.jd index b0497cda4da11..98e2afd3f4d92 100644 --- a/docs/html-intl/intl/ko/training/basics/activity-lifecycle/pausing.jd +++ b/docs/html-intl/intl/ko/training/basics/activity-lifecycle/pausing.jd @@ -8,13 +8,13 @@ trainingnavtop=true
    - +

    이 과정에서 다루는 내용

    1. 액티비티 일지정지하기
    2. 액티비티 재개하기
    - +

    필독 항목

    -

    일반적인 앱 사용 중에 가끔 다른 +

    일반적인 앱 사용 중에 가끔 다른 비주얼 구성요소로 인해 전면의 액티비티가 일시정지되는 경우가 있습니다. 예를 들어, 대화 상자 스타일과 같은 반투명 액티비티가 열리면, 그 이전 액티비티는 일시정지됩니다. 액티비티가 부분적으로 보이지만 현재 포커스 내에 있지 않는 한 일시정지된 상태로 유지됩니다.

    @@ -59,7 +59,7 @@ android.app.Activity#onPause()}에 대한 호출을 수신하는 경우, 이는

    액티비티 일지정지하기

    - +

    시스템이 액티비티에 대해 {@link android.app.Activity#onPause()}를 호출하면, 이는 엄밀해 말해 액티비티가 여전히 부분적으로 보일 수 있음을 의미하지만, 대개의 경우 사용자가 액티비티를 떠나 곧 정지 상태로 전환될 것임을 나타냅니다. 일반적으로 다음 작업을 수행할 때 diff --git a/docs/html-intl/intl/ko/training/basics/activity-lifecycle/recreating.jd b/docs/html-intl/intl/ko/training/basics/activity-lifecycle/recreating.jd index 79fb92bbdc7d9..2408cac248bb1 100644 --- a/docs/html-intl/intl/ko/training/basics/activity-lifecycle/recreating.jd +++ b/docs/html-intl/intl/ko/training/basics/activity-lifecycle/recreating.jd @@ -8,13 +8,13 @@ trainingnavtop=true

    - +

    이 과정에서 다루는 내용

    1. 액티비티 상태 저장하기
    2. 액티비티 상태 복원하기
    - +

    필독 항목

    -
    +

    기기 상태 변경을 모니터링하는 가장 간단한 방법은 모니터링하는 각 상태에 대해 {@link android.content.BroadcastReceiver}를 만들어 각각을 애플리케이션 매니페스트에 등록하는 것입니다. 그러면 각 리시버 내에서 현재 기기 상태를 기반으로 반복 알람의 일정을 간단히 변경할 수 있습니다.

    @@ -31,10 +31,10 @@ previous.link=connectivity-monitoring.html

    이 방법의 부작용은 리시버 중 하나라도 실행되면 매번 앱이 기기의 절전 모드를 해제시킨다는 것입니다.

    더 나은 방법은 런타임 때 브로드캐스트 리시버를 사용 중지 또는 사용하도록 설정하는 것입니다. 이렇게 하면 매니페스트에 선언한 리시버를 필요할 때만 시스템 이벤트에 의해 실행되는 수동적인 알람으로 사용할 수 있습니다.

    - -

    효율성 향상을 위한 상태 변화 수신기의 전환 및 단계적 연결

    - + +

    효율성 향상을 위한 상태 변화 수신기의 전환 및 단계적 연결

    +

    {@link android.content.pm.PackageManager}를 사용하여 아래에서 표시된 대로 모든 사용 또는 사용 중지하기 원하는 브로드캐스트 리시버를 포함하여 매니페스트 내에 정의된 모든 요소의 사용 가능 상태를 전환할 수 있습니다.

    ComponentName receiver = new ComponentName(context, myReceiver.class);
    diff --git a/docs/html-intl/intl/ko/training/multiscreen/adaptui.jd b/docs/html-intl/intl/ko/training/multiscreen/adaptui.jd
    index cb7b66c90238b..a8d2fc16939f5 100644
    --- a/docs/html-intl/intl/ko/training/multiscreen/adaptui.jd
    +++ b/docs/html-intl/intl/ko/training/multiscreen/adaptui.jd
    @@ -10,9 +10,9 @@ previous.link=screendensities.html
     
     
     
    -
    -
    - +
    +
    +

    강의 목표

      @@ -27,17 +27,17 @@ previous.link=screendensities.html - +

      다운로드

      - +
      샘플 앱 다운로드 -

      NewsReader.zip

      -
      - - -
    -
    +

    NewsReader.zip

    +
    + + +
    +

    현재 애플리케이션이 표시하는 레이아웃에 따라 UI 플로가 달라질 수 있습니다. 예를 들어 애플리케이션이 이중 창 모드로 되어 있는 경우에는 왼쪽 창에 있는 항목을 클릭하면 오른쪽 창에 콘텐츠가 표시되고, 단일 창 모드로 되어 있는 경우에는 콘텐츠가 해당 창에 표시됩니다(다른 액티비티에서).

    @@ -56,7 +56,7 @@ public class NewsReaderActivity extends FragmentActivity { setContentView(R.layout.main_layout); View articleView = findViewById(R.id.article); - mIsDualPane = articleView != null && + mIsDualPane = articleView != null && articleView.getVisibility() == View.VISIBLE; } } @@ -116,7 +116,7 @@ public void onCreate(Bundle savedInstanceState) { else { /* use list navigation (spinner) */ actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST); - SpinnerAdapter adap = new ArrayAdapter(this, + SpinnerAdapter adap = new ArrayAdapter(this, R.layout.headline_item, CATEGORIES); actionBar.setListNavigationCallbacks(adap, handler); } @@ -168,7 +168,7 @@ public class HeadlinesFragment extends ListFragment { public class HeadlinesFragment extends ListFragment { ... @Override - public void onItemClick(AdapterView<?> parent, + public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (null != mHeadlineSelectedListener) { mHeadlineSelectedListener.onHeadlineSelected(position); diff --git a/docs/html-intl/intl/ko/training/multiscreen/index.jd b/docs/html-intl/intl/ko/training/multiscreen/index.jd index dd152aea410aa..0a30f92abaab5 100644 --- a/docs/html-intl/intl/ko/training/multiscreen/index.jd +++ b/docs/html-intl/intl/ko/training/multiscreen/index.jd @@ -7,10 +7,10 @@ next.link=screensizes.html @jd:body -
    -
    - -

    요구사항과 선행조건

    +
    +
    + +

    요구사항과 선행조건

    • Android 1.6 이상(샘플 앱의 경우 2.1 이상)
    • @@ -27,17 +27,17 @@ href="{@docRoot}tools/support-library/index.html">호환성 라이브러리 - -

      다운로드

      - -
      + +

      다운로드

      + +
      샘플 앱 다운로드 -

      NewsReader.zip

      -
      - -
      -
    - +

    NewsReader.zip

    +
    + +
    +
    +

    Android는 소형 휴대전화에서부터 대형 TV에 이르기까지 다양한 화면 크기의 수많은 기기 유형을 지원합니다. 따라서 애플리케이션이 모든 화면 크기와 호환되어 최대한 많은 사용자가 사용할 수 있도록 디자인하는 것이 중요합니다.

    하지만 다양한 기기 유형과 호환되는 것만으로는 충분하지 않습니다. 각 화면 크기에 따라 사용자 상호작용에 유리한 점과 불리한 점이 다릅니다. 따라서 사용자에게 만족을 주고 깊은 인상을 심어주려면 애플리케이션이 단지 여러 화면을 지원하는 데 그치지 않고 화면 구성별로 사용자 환경을 최적화해야 합니다.

    @@ -48,17 +48,17 @@ href="{@docRoot}tools/support-library/index.html">호환성 라이브러리

    참고: 이 강의 및 강의와 관련된 샘플은 호환성 라이브러리를 사용하며 이는 Android 3.0 이하 버전에서 {@link android.app.Fragment} API를 사용하기 위해서입니다. 이 강의에서 API를 모두 사용하려면 라이브러리를 다운로드하여 애플리케이션에 추가해야 합니다.

    - -

    강의

    - -
    -
    다양한 화면 크기 지원
    -
    이 강의에서는 여러 다양한 화면 크기에 조정되는 레이아웃을 디자인하는 방법(유연한 보기 크기, {@link android.widget.RelativeLayout}, 화면 크기 및 방향 한정자, 별칭 필터 및 나인-패치 비트맵 사용하기)을 안내합니다.
    - -
    다양한 화면 밀도 지원
    -
    이 강의에서는 다양한 픽셀 밀도를 가진 화면을 지원하는 방법(밀도 독립형 픽셀(density-independent pixel) 사용하기 및 밀도별로 적합한 비트맵 제공하기)을 설명합니다.
    - -
    조정형 UI 플로우 구현
    -
    이 강의에서는 여러 화면 크기/밀도 조합에 조정되도록 UI 플로우를 구현하는 방법(활성 레이아웃의 런타임 감지, 현재 레이아웃에 따른 대응, 화면 구성 변경 처리)을 설명합니다.
    -
    + +

    강의

    + +
    +
    다양한 화면 크기 지원
    +
    이 강의에서는 여러 다양한 화면 크기에 조정되는 레이아웃을 디자인하는 방법(유연한 보기 크기, {@link android.widget.RelativeLayout}, 화면 크기 및 방향 한정자, 별칭 필터 및 나인-패치 비트맵 사용하기)을 안내합니다.
    + +
    다양한 화면 밀도 지원
    +
    이 강의에서는 다양한 픽셀 밀도를 가진 화면을 지원하는 방법(밀도 독립형 픽셀(density-independent pixel) 사용하기 및 밀도별로 적합한 비트맵 제공하기)을 설명합니다.
    + +
    조정형 UI 플로우 구현
    +
    이 강의에서는 여러 화면 크기/밀도 조합에 조정되도록 UI 플로우를 구현하는 방법(활성 레이아웃의 런타임 감지, 현재 레이아웃에 따른 대응, 화면 구성 변경 처리)을 설명합니다.
    +
    diff --git a/docs/html-intl/intl/ko/training/multiscreen/screendensities.jd b/docs/html-intl/intl/ko/training/multiscreen/screendensities.jd index 5d6e2f3c59b78..dfaa44f33abc7 100644 --- a/docs/html-intl/intl/ko/training/multiscreen/screendensities.jd +++ b/docs/html-intl/intl/ko/training/multiscreen/screendensities.jd @@ -12,8 +12,8 @@ next.link=adaptui.html -
    -
    +
    +

    강의 목표

      @@ -29,15 +29,15 @@ next.link=adaptui.html

      다운로드

      - -
      + +
      샘플 앱 다운로드 -

      NewsReader.zip

      -
      - - -
      -
    +

    NewsReader.zip

    +
    + + +
    +

    이 강의에서는 다양한 리소스를 제공하고 해상도 독립형(resolution-independent) 측정 단위를 사용함으로써 다양한 화면 밀도를 지원하는 방법을 설명합니다.

    @@ -48,8 +48,8 @@ next.link=adaptui.html

    예를 들어 두 개의 보기 사이에 여백을 지정할 때 px가 아닌 dp를 사용합니다.

    -<Button android:layout_width="wrap_content" 
    -    android:layout_height="wrap_content" 
    +<Button android:layout_width="wrap_content"
    +    android:layout_height="wrap_content"
         android:text="@string/clickme"
         android:layout_marginTop="20dp" />
     
    @@ -57,8 +57,8 @@ next.link=adaptui.html

    텍스트 크기를 지정할 때에는 항상 sp를 사용합니다.

    -<TextView android:layout_width="match_parent" 
    -    android:layout_height="wrap_content" 
    +<TextView android:layout_width="match_parent"
    +    android:layout_height="wrap_content"
         android:textSize="20sp" />
     
    diff --git a/docs/html-intl/intl/ko/training/multiscreen/screensizes.jd b/docs/html-intl/intl/ko/training/multiscreen/screensizes.jd index f2e77a6e2b04b..984923d5ee935 100644 --- a/docs/html-intl/intl/ko/training/multiscreen/screensizes.jd +++ b/docs/html-intl/intl/ko/training/multiscreen/screensizes.jd @@ -10,8 +10,8 @@ next.link=screendensities.html -
    -
    +
    +

    강의 목표

      @@ -30,26 +30,26 @@ next.link=screendensities.html
    1. 다양한 화면 지원
    2. -

      다운로드

      - -
      +

      다운로드

      + +
      샘플 앱 다운로드 -

      NewsReader.zip

      -
      - -
      -
    +

    NewsReader.zip

    +
    + +
    +

    이 강의에서는 다양한 화면 크기를 지원하는 방법을 설명합니다.

    -
      -
    • 화면에 맞게 레이아웃 크기 조정
    • -
    • 화면 구성에 따라 적합한 UI 레이아웃 제공
    • +
        +
      • 화면에 맞게 레이아웃 크기 조정
      • +
      • 화면 구성에 따라 적합한 UI 레이아웃 제공
      • 올바른 화면에 올바른 레이아웃 적용
      • -
      • 정확하게 확대되는 비트맵 제공
      • -
      +
    • 정확하게 확대되는 비트맵 제공
    • +
    -

    'wrap_content' 및 'match_parent' 사용

    +

    'wrap_content' 및 'match_parent' 사용

    레이아웃이 다양한 화면 크기에 따라 유연하게 조정되도록 하려면 일부 뷰 구성요소의 너비와 높이에 "wrap_content""match_parent"를 사용해야 합니다. "wrap_content"를 사용하면 뷰의 너비와 높이가 해당 뷰 내에 콘텐츠가 들어가는데 필요한 최소 크기로 설정되는 반면, "match_parent"(API 수준 8 이전에는 "fill_parent"라고도 함)를 사용하면 구성요소가 확장되어 부모뷰의 크기와 일치하게 됩니다.

    @@ -65,7 +65,7 @@ next.link=screendensities.html

    그림 1. 세로 모드(왼쪽) 및 가로 모드(오른쪽)에서의 뉴스 리더 샘플 앱

    -

    RelativeLayout 사용

    +

    RelativeLayout 사용

    비교적 복잡한 레이아웃을 만들려면 {@link android.widget.LinearLayout}의 중첩 인스턴스와 "wrap_content""match_parent" 크기의 조합을 사용합니다. 하지만 {@link android.widget.LinearLayout} 을 사용하면 자식뷰의 여백 관계를 정확하게 제어할 수 없으며 {@link android.widget.LinearLayout} 단순히 나란하게 표시됩니다. 자식뷰를 일직선이 아닌 다양한 방향으로 표시해야 하는 경우 구성요소 사이의 여백 관계를 중심으로 레이아웃을 지정할 수 있는 {@link android.widget.RelativeLayout}을 사용하는 것이 더 좋은 방법일 수 있습니다. 예를 들어 화면 왼쪽에 하나의 자식뷰를, 오른쪽에 다른 자식뷰를 정렬할 수 있습니다.

    @@ -115,8 +115,8 @@ next.link=screendensities.html

    구성요소의 크기가 변하더라도 여백 관계가 {@link android.widget.RelativeLayout.LayoutParams}.

    - -

    크기 한정자 사용

    + +

    크기 한정자 사용

    이전 섹션에서 다룬 유연한 레이아웃이나 상대적 레이아웃으로는 한계가 있습니다. 이러한 레이아웃이 구성요소 내부 및 주위의 여백을 확장하여 다양한 화면에 맞게 조정되긴 하지만 화면 크기별로 최적의 사용자 환경을 제공하지는 못할 수 있습니다. 따라서 애플리케이션은 유연한 레이아웃을 구현할 뿐 아니라 다양한 화면 구성을 타겟팅할 수 있도록 다양한 대체 레이아웃을 제공해야 합니다. 그 방법은 런타임이 현재 기기의 구성에 따라 적합한 리소스(예: 화면 크기별로 다른 레이아웃 디자인)를 자동으로 선택하도록 해 주는 구성 한정자를 사용하는 것입니다.

    @@ -158,7 +158,7 @@ next.link=screendensities.html

    하지만 Android 3.2 이전 기기는 sw600dp를 크기 한정자로 인식하지 않기 때문에 최소 너비 한정자가 제대로 작동하지 않으며 따라서 large 한정자도 계속 사용해야 합니다. 따라서 res/layout-large/main.xml라는 이름의 파일이 있어야 하며 이 파일은 res/layout-sw600dp/main.xml과 동일한 파일입니다. 다음 섹션에서는 이런 식으로 레이아웃 파일이 중복되지 않게 하는 기술을 살펴보겠습니다.

    -

    레이아웃 별칭 사용

    +

    레이아웃 별칭 사용

    최소 너비 한정자는 Android 3.2 이상 버전에서만 사용할 수 있습니다. 따라서 이전 버전과 호환되도록 하려면 추상화 크기 빈(소형, 보통, 대형 및 초대형)을 계속 사용해야 합니다. 예를 들어 휴대전화에서는 단일 창 UI가 표시되고 7인치 태블릿, TV 및 기타 대형 기기에서는 다중 창 UI가 표시되도록 UI를 디자인하려면 다음 파일을 제공해야 합니다.

    @@ -202,7 +202,7 @@ next.link=screendensities.html {@code large},3.2 이후 버전은 sw600dp와 일치).

    -

    방향 한정자 사용

    +

    방향 한정자 사용

    일부 레이아웃은 가로 및 세로 방향 모두에서 잘 작동하지만 대부분의 레이아웃은 조정을 통해 많은 이점을 누릴 수 있습니다. 다음은 뉴스 리더 샘플 앱에서 화면 크기와 방향별로 레이아웃이 어떻게 작동하는지 보여줍니다.

    diff --git a/docs/html-intl/intl/pt-br/about/versions/android-5.0.jd b/docs/html-intl/intl/pt-br/about/versions/android-5.0.jd index 23904b3325efa..5408793c79e95 100644 --- a/docs/html-intl/intl/pt-br/about/versions/android-5.0.jd +++ b/docs/html-intl/intl/pt-br/about/versions/android-5.0.jd @@ -426,7 +426,7 @@ sdk.platform.apiLevel=21

    Quando o sistema detectar uma rede adequada, ele se conectará à rede e chamará a chamada de retorno {@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()}. É possível usar o objeto {@link android.net.Network} da chamada de retorno a fim de receber mais informações sobre a rede ou direcionar o tráfego para que a rede selecionada seja usada.

    Bluetooth Low Energy

    -

    O Android 4.3 apresentou o suporte de plataforma para o Bluetooth Low Energy(Bluetooth LE) na função central. No Android 5.0, um dispositivo Android agora pode agir como um dispositivo periférico de Bluetooth LE. Os apps podem usar esse recurso para fazer com que sua presença seja percebida pelos dispositivos vizinhos. É possível, por exemplo, criar apps que permitem que um dispositivo funcione como um pedômetro ou um monitor de integridade de dados e envie seus dados para outro dispositivo Bluetooth LE.

    +

    O Android 4.3 apresentou o suporte de plataforma para o Bluetooth Low Energy(Bluetooth LE) na função central. No Android 5.0, um dispositivo Android agora pode agir como um dispositivo periférico de Bluetooth LE. Os apps podem usar esse recurso para fazer com que sua presença seja percebida pelos dispositivos vizinhos. É possível, por exemplo, criar apps que permitem que um dispositivo funcione como um pedômetro ou um monitor de integridade de dados e envie seus dados para outro dispositivo Bluetooth LE.

    As novas APIs de {@link android.bluetooth.le} permitem que seus apps divulguem anúncios, verifiquem respostas e formem conexões com dispositivos Bluetooth LE vizinhos. Para usar os novos recursos de publicidade e varredura, adicione a permissão {@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN} no manifesto. Quando os usuários atualizam ou fazem o download do seu app a partir da Play Store, eles são solicitados a conceder a seguinte permissão para seu app: "Informações da conexão Bluetooth: permite que o app controle o Bluetooth, incluindo a divulgação para dispositivos Bluetooth vizinhos ou a busca de informações sobre esses dispositivos."

    Para começar a publicidade de Bluetooth LE para que outros dispositivos possam descobrir seu app, chame {@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()} e passe uma implementação da classe {@link android.bluetooth.le.AdvertiseCallback}. O objeto de chamada de retorno recebe um relatório do sucesso ou da falha da operação de publicidade.

    diff --git a/docs/html-intl/intl/pt-br/design/get-started/principles.jd b/docs/html-intl/intl/pt-br/design/get-started/principles.jd index 82e28cccfe10c..81b3524130e0e 100644 --- a/docs/html-intl/intl/pt-br/design/get-started/principles.jd +++ b/docs/html-intl/intl/pt-br/design/get-started/principles.jd @@ -8,7 +8,7 @@ definir as diretrizes de projeto mais detalhadas para diferentes tipos de dispositivo.

    -Considere estes princípios ao aplicar +Considere estes princípios ao aplicar sua criatividade e sua mentalidade de projeto. Desvie-se de forma objetiva.

    @@ -18,7 +18,7 @@ sua criatividade e sua mentalidade de projeto. Desvie-se de forma objetiva.

    Agrade-me de formas surpreendentes

    -

    Uma bela superfície, uma animação cuidadosamente posicionada ou um efeito sonoro no momento certo +

    Uma bela superfície, uma animação cuidadosamente posicionada ou um efeito sonoro no momento certo contribui para a boa experiência. Efeitos sutis contribuem para uma sensação de facilidade e de que algo poderoso está à mão.

    diff --git a/docs/html-intl/intl/pt-br/design/material/index.jd b/docs/html-intl/intl/pt-br/design/material/index.jd index 5368d2d74c0c9..e2f0b47de6e96 100644 --- a/docs/html-intl/intl/pt-br/design/material/index.jd +++ b/docs/html-intl/intl/pt-br/design/material/index.jd @@ -39,10 +39,10 @@ page.image=images/cards/design-material-for-android_2x.jpg -

    O Material Design é um guia abrangente para design visual, de movimento e de +

    O Material Design é um guia abrangente para design visual, de movimento e de interação para diversas plataformas e dispositivos. O Android agora é compatível com -aplicativos do Material Design. Para usar o Material Design nos aplicativos Android, siga as orientações definidas -nas especificações do Material Design e use os novos +aplicativos do Material Design. Para usar o Material Design nos aplicativos Android, siga as orientações definidas +nas especificações do Material Design e use os novos componentes e funcionalidades disponíveis no Android 5.0 (API de nível 21) e em posteriores.

    O Android fornece os seguintes elementos para criar aplicativos do Material Design:

    @@ -59,7 +59,7 @@ componentes e funcionalidades disponíveis no Android 5.0 (API de nível 21) e e

    Tema do Material

    -

    O tema do Material fornece um novo estilo para o seu aplicativo, widgets de sistema que permitem +

    O tema do Material fornece um novo estilo para o seu aplicativo, widgets de sistema que permitem definir a paleta de cores e as animações padrão para feedback de toque e transições de atividades.

    @@ -79,13 +79,13 @@ definir a paleta de cores e as animações padrão para feedback de toque e tran
    -

    Para obter mais informações, consulte Como usar o tema +

    Para obter mais informações, consulte Como usar o tema do Material.

    Listas e cartões

    -

    O Android fornece dois novos widgets para exibir cartões e listas com estilos e animações do +

    O Android fornece dois novos widgets para exibir cartões e listas com estilos e animações do Material Design:

    @@ -97,19 +97,19 @@ Material Design:

    -

    O novo widget CardView permite exibir informações importantes dentro de +

    O novo widget CardView permite exibir informações importantes dentro de cartões que têm aparência consistente.


    -

    Para obter mais informações, consulte Como criar +

    Para obter mais informações, consulte Como criar listas e cartões.

    Sombras de vistas

    -

    Além das propriedades X e Y, vistas no Android agora têm uma propriedade +

    Além das propriedades X e Y, vistas no Android agora têm uma propriedade Z. Essa nova propriedade representa a elevação de uma vista, que determina:

    -

    Para obter mais informações, consulte Como trabalhar +

    Para obter mais informações, consulte Como trabalhar com desenháveis.

    diff --git a/docs/html-intl/intl/pt-br/design/patterns/compatibility.jd b/docs/html-intl/intl/pt-br/design/patterns/compatibility.jd index 775af0c312a0e..bd4ec30ab1ed7 100644 --- a/docs/html-intl/intl/pt-br/design/patterns/compatibility.jd +++ b/docs/html-intl/intl/pt-br/design/patterns/compatibility.jd @@ -57,7 +57,7 @@ de ações resultante tem o mesmo estilo que no exemplo anterior, mas é exibida

    Aplicativos legados em telefones com controles de navegação virtuais

    -

    Ao executar um aplicativo que foi desenvolvido para Android 2.3 ou anterior em um telefone com controles de +

    Ao executar um aplicativo que foi desenvolvido para Android 2.3 ou anterior em um telefone com controles de navegação virtuais, um controle de ações adicionais é exibido no lado direito da barra de navegação virtual. É possível tocar no controle para exibir as ações do aplicativo no estilo tradicional de menu do Android.

    diff --git a/docs/html-intl/intl/pt-br/design/patterns/navigation.jd b/docs/html-intl/intl/pt-br/design/patterns/navigation.jd index 8ed12f71b60b7..89eab9a4a19ee 100644 --- a/docs/html-intl/intl/pt-br/design/patterns/navigation.jd +++ b/docs/html-intl/intl/pt-br/design/patterns/navigation.jd @@ -66,7 +66,7 @@ estará no mesmo lugar dentro da hierarquia do aplicativo e nenhum histórico de
  • Mudar características de exibição (como mudar o zoom)
  • Navegação entre telas de mesmo nível

    -

    Quando o aplicativo suporta navegação de uma lista de itens para uma vista de detalhes de um desses itens, +

    Quando o aplicativo suporta navegação de uma lista de itens para uma vista de detalhes de um desses itens, frequentemente é desejável dar suporte à navegação de direção daquele item para outro anterior ou posterior a ele na lista. Por exemplo, no Gmail, é fácil deslizar para a esquerda ou para a direita em uma conversa para visualizar uma mais nova ou mais antiga na mesma Caixa de entrada. Assim como ao mudar a vista dentro de uma tela, tal @@ -82,9 +82,9 @@ ignorar essas telas relacionadas e navegar para a tela do contêiner visualizada -

    Você tem a capacidade de deixar o comportamento de Para Cima ainda mais inteligente com base em seu conhecimento da +

    Você tem a capacidade de deixar o comportamento de Para Cima ainda mais inteligente com base em seu conhecimento da vista de detalhe. Estendendo o exemplo da Play Store acima, imagine que o usuário navegou do último -Livro visualizado para os detalhes da adaptação do Filme. Nesse caso, Para Cima pode retornar a um contêiner +Livro visualizado para os detalhes da adaptação do Filme. Nesse caso, Para Cima pode retornar a um contêiner (filmes) pelo qual o usuário não navegou anteriormente.

    @@ -116,7 +116,7 @@ botão Voltar continua até a Tela inicial.

    Notificações indiretas

    -

    Quando o aplicativo precisa apresentar simultaneamente informações sobre vários eventos, ele pode usar +

    Quando o aplicativo precisa apresentar simultaneamente informações sobre vários eventos, ele pode usar uma única notificação que direcione o usuário a uma tela intersticial. Essa tela resume esses eventos e fornece caminhos para que o usuário mergulhe profundamente no aplicativo. Notificações desse estilo são chamadas de notificações indiretas.

    @@ -128,7 +128,7 @@ tela intersticial, Para Cima e Voltar se comportam como em notificações padrã navegando dentro do aplicativo em vez de voltar à tela intersticial.

    Por exemplo, suponha que um usuário no Gmail receba uma notificação indireta do Agenda. Tocar nessa -notificação abrirá a tela intersticial, que exibirá lembretes para vários +notificação abrirá a tela intersticial, que exibirá lembretes para vários eventos. Tocar em Voltar na tela intersticial retornará o usuário ao Gmail. Tocar em um determinado evento levará o usuário da tela intersticial ao aplicativo completo do Agenda para exibir detalhes do evento. Dos detalhes do evento, Para Cima e Voltar navegam para a vista de nível superior do Agenda.

    @@ -169,7 +169,7 @@ informações e todas as ações associadas que o usuário pode executar. Seu ap atividades, consistindo em atividades que você cria e naquelas que reutiliza de outros aplicativos.

    Uma tarefa é a sequência de atividades que um usuário segue para atingir um objetivo. Uma -única tarefa pode usar atividades apenas de um aplicativo ou pode retirar atividades de uma série +única tarefa pode usar atividades apenas de um aplicativo ou pode retirar atividades de uma série de outros aplicativos.

    Uma intenção é um mecanismo para que um aplicativo sinalize que gostaria a assistência de outro @@ -188,7 +188,7 @@ que foram registradas para tratar a intenção Compartilhar.

    -

    Quando o usuário seleciona o compartilhamento via Gmail, a atividade de composição do Gmail é adicionada como uma continuação da +

    Quando o usuário seleciona o compartilhamento via Gmail, a atividade de composição do Gmail é adicionada como uma continuação da Tarefa A — nenhuma tarefa nova é criada. Se o Gmail tivesse a própria tarefa em execução em segundo plano, ela não seria afetada.

    @@ -209,5 +209,5 @@ Recentes). Se o Gmail já tivesse a própria tarefa em execução em segundo pla pela Tarefa B — o contexto anterior é abandonado em favor do novo objetivo do usuário.

    Quando o aplicativo é registrado para tratar intenções com uma atividade em um ponto profundo da hierarquia do aplicativo, -consulte Navegação para o seu aplicativo pelos widgets de tela +consulte Navegação para o seu aplicativo pelos widgets de tela inicial e notificações para ver orientações sobre como especificar a navegação Para Cima.

    diff --git a/docs/html-intl/intl/pt-br/design/patterns/notifications.jd b/docs/html-intl/intl/pt-br/design/patterns/notifications.jd index efea6104638c4..5560e85f5c2eb 100644 --- a/docs/html-intl/intl/pt-br/design/patterns/notifications.jd +++ b/docs/html-intl/intl/pt-br/design/patterns/notifications.jd @@ -43,12 +43,12 @@ atenção — e que é sincronizado conforme apropriado em todos os disposit funcionais:

    -

    Como escolher uma prioridade +

    Como escolher uma prioridade adequada

    -

    DEFAULT, HIGH e MAX são níveis de prioridade de interrupção e arriscam +

    DEFAULT, HIGH e MAX 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:

    @@ -359,7 +359,7 @@ de notificação), podem usar essas informações para tomar decisões de classi href="/reference/android/app/Notification.html#CATEGORY_CALL">CATEGORY_CALL

    -

    Chamada recebida (voz ou vídeo) ou solicitação similar de +

    Chamada recebida (voz ou vídeo) ou solicitação similar de comunicação síncrona

    @@ -508,7 +508,7 @@ de um determinado tipo estão pendentes.

    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 +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 @@ -525,13 +525,13 @@ opcionais

    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 +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.

    Use ícones distintos

    Ao olhar para a área de notificação, o usuário deverá ser capaz de discernir -que tipos de +que tipos de notificações estão atualmente pendentes.

    @@ -545,7 +545,7 @@ aplicativo que tenham aparência suficientemente distinta.

    O que fazer

    Use o estilo de ícone de notificação apropriado - para ícones pequenos e o + para ícones pequenos e o estilo de ícone de barra de ação da luminosidade do Material para os ícones de ação.

    @@ -564,7 +564,7 @@ opacidade total.

    O que não fazer

    -

    Use cores para distinguir o seu aplicativo dos outros. Ícones de notificação devem +

    Use cores para distinguir o seu aplicativo dos outros. Ícones de notificação devem somente ser uma imagem com fundo branco sobre transparente.

    @@ -599,7 +599,7 @@ aplicativo exige. Portanto, use notificações de forma cuidadosa.

    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 +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 é @@ -617,7 +617,7 @@ alguma outra coisa.

    Exemplos de notificação que depende de tempo

    -

    Apesar de aplicativos bem comportados geralmente se manifestarem apenas quando ocorre interação com eles, alguns +

    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.

    Use notificações principalmente para eventos que dependam de tempo, especialmente @@ -625,11 +625,11 @@ casos justificam que o aplicativo interrompa o usuário com uma notificação n 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 +notificação e atrair a atenção do usuário, pois o evento é iminente e eventos de calendário frequentemente envolvem outras pessoas.

    -

    Quando não exibir +

    Quando não exibir uma notificação

    @@ -646,8 +646,8 @@ 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. -
  • Não crie uma notificação se as informações novas relevantes estiverem -atualmente na tela. Em vez disso, +
  • 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 @@ -655,12 +655,12 @@ usuário estiver conversando ativamente com outro usuário.
  • 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.
  • -
  • 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 +
  • 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.
  • 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 +aplicativo. Uma notificação deve fornecer informações úteis, oportunas e novas e não deve ser usada meramente para executar um aplicativo.
  • Não crie notificações supérfluas apenas para colocar sua marca na frente @@ -673,7 +673,7 @@ com o seu tela inicial.
  • -

    Interação com +

    Interação com notificações

    Notificações são indicadas por ícones na barra de status e podem ser acessadas @@ -692,7 +692,7 @@ Deslizar à esquerda ou à direita em uma notificação a remove da gaveta.

    Notificações contínuas mantêm os usuários informados sobre um processo em andamento em -segundo plano. +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 @@ -701,7 +701,7 @@ feedback sobre tarefas mais longas, como o download de um arquivo ou a codifica manualmente uma notificação contínua da gaveta de notificações.

    Reprodução de mídia

    -

    No Android 5.0, a tela de bloqueio não mostra controles de transporte por causa da classe +

    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 mostra 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 @@ -724,12 +724,12 @@ Para obter orientação adicional sobre o uso de caixas de diálogo e avisos, co

    Notificações são notícias e, portanto, são essencialmente exibidas em ordem cronológica inversa, com -consideração especial para a +consideração especial para a prioridade da notificação declarada no aplicativo.

    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, +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 @@ -762,14 +762,14 @@ recebem

    Na tela de bloqueio

    -

    Como as notificações são visíveis na tela de bloqueio, a privacidade do usuário é uma consideração +

    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 + 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.

      -
    • Para dispositivos que têm uma tela de bloqueio segura (PIN, padrão ou senha), a interface tem +
    • 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.
    • @@ -828,7 +828,7 @@ 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 +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 diff --git a/docs/html-intl/intl/pt-br/guide/components/bound-services.jd b/docs/html-intl/intl/pt-br/guide/components/bound-services.jd index aa024943160f9..032950eb962bb 100644 --- a/docs/html-intl/intl/pt-br/guide/components/bound-services.jd +++ b/docs/html-intl/intl/pt-br/guide/components/bound-services.jd @@ -334,7 +334,7 @@ que o serviço realize vários encadeamentos, deve-se usar a estendendo a classe Binder para que tudo que ele tenha que fazer seja lançar o {@link android.os.IBinder} retornado para a classe {@code LocalService} e solicitar a instância de {@code LocalService}:

      @@ -637,7 +637,7 @@ android.content.Context#stopService stopService()}, independente de vínculo com qualquer cliente.

      Além disso, se o serviço for iniciado e aceitar vínculos, quando o sistema chamar -o método {@link android.app.Service#onUnbind onUnbind()}, será possível retornar +o método {@link android.app.Service#onUnbind onUnbind()}, será possível retornar {@code true} opcionalmente se você quiser receber uma chamada de {@link android.app.Service#onRebind onRebind()} na próxima vez em que um cliente vincular-se ao serviço (em vez de receber uma chamada de {@link android.app.Service#onBind onBind()}). {@link android.app.Service#onRebind diff --git a/docs/html-intl/intl/pt-br/guide/components/fragments.jd b/docs/html-intl/intl/pt-br/guide/components/fragments.jd index 7b1acf9e3439c..74f3dfe2d15b3 100644 --- a/docs/html-intl/intl/pt-br/guide/components/fragments.jd +++ b/docs/html-intl/intl/pt-br/guide/components/fragments.jd @@ -36,7 +36,7 @@ parent.link=activities.html

    • {@link android.app.FragmentManager}
    • {@link android.app.FragmentTransaction}
    • - +

      Veja também

      1. Construção de uma IU dinâmica com Fragmentos
      2. @@ -361,8 +361,8 @@ você precisará usar {@link android.app.FragmentManager#findFragmentByTag findFragmentByTag()}.

        Para ver uma atividade de exemplo que usa um fragmento como um trabalhador de segundo plano, sem uma IU, consulte o exemplo de {@code -FragmentRetainInstance.java}, incluso nos exemplos do SDK (disponibilizados pelo -Android SDK Manager) e localizado no sistema como +FragmentRetainInstance.java}, incluso nos exemplos do SDK (disponibilizados pelo +Android SDK Manager) e localizado no sistema como <sdk_root>/APIDemos/app/src/main/java/com/example/android/apis/app/FragmentRetainInstance.java.

        @@ -378,7 +378,7 @@ chame {@link android.app.Activity#getFragmentManager()} a partir da atividade.Adquirir fragmentos existentes na atividade, com {@link android.app.FragmentManager#findFragmentById findFragmentById()} (para fragmentos que forneçam uma IU no layout da atividade) ou {@link android.app.FragmentManager#findFragmentByTag -findFragmentByTag()} (para fragmentos que forneçam ou não uma IU). +findFragmentByTag()} (para fragmentos que forneçam ou não uma IU).
      3. Retire os fragmentos da pilha de retorno com {@link android.app.FragmentManager#popBackStack()} (simulando um comando de Voltar do usuário).
      4. Registre uma escuta para as alterações na pilha de retorno com {@link @@ -600,7 +600,7 @@ como usar o provedor de conteúdo estão disponíveis na documentação Adição de itens à barra de ação -

        Os fragmentos podem contribuir com itens de menu para o menu de opções da atividade (e, consequentemente, para a barra de ação) implementando +

        Os fragmentos podem contribuir com itens de menu para o menu de opções da atividade (e, consequentemente, para a barra de ação) implementando {@link android.app.Fragment#onCreateOptionsMenu(Menu,MenuInflater) onCreateOptionsMenu()}. Para que este método receba chamadas, no entanto, você deve chamar {@link android.app.Fragment#setHasOptionsMenu(boolean) setHasOptionsMenu()} durante {@link @@ -785,7 +785,7 @@ android.widget.FrameLayout}), ou iniciar uma nova atividade (onde o fragmento po

        O segundo fragmento, {@code DetailsFragment}, exibe o resumo da peça para o item selecionado na lista de {@code TitlesFragment}:

        - + {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details}

        Uma nova chamada da classe {@code TitlesFragment}, ou seja, se o usuário clicar em um item de lista @@ -798,7 +798,7 @@ o resumo da peça selecionada quando a tela está na orientação de retrato:

        Observe que esta atividade finaliza-se se a configuração for de paisagem, pois a atividade principal pode tomar o controle e exibir {@code DetailsFragment} juntamente com {@code TitlesFragment}. Isto pode acontecer se o usuário iniciar {@code DetailsActivity} enquanto estiver na orientação de retrato, diff --git a/docs/html-intl/intl/pt-br/guide/components/fundamentals.jd b/docs/html-intl/intl/pt-br/guide/components/fundamentals.jd index 47b98458e6429..2fb85531de8a6 100644 --- a/docs/html-intl/intl/pt-br/guide/components/fundamentals.jd +++ b/docs/html-intl/intl/pt-br/guide/components/fundamentals.jd @@ -379,7 +379,7 @@ mas serviços externos, como o Google Play, as leem para oferecer uma filtragem aos usuários quando buscam esses aplicativos para seu dispositivo.

        Por exemplo: se o aplicativo exige uma câmera e usa APIs introduzidas no Android 2.1 (API de nível 7), -deve-se declarar esses requisitos no arquivo de manifesto da seguinte forma:

        +deve-se declarar esses requisitos no arquivo de manifesto da seguinte forma:

         <manifest ... >
        @@ -393,7 +393,7 @@ deve-se declarar esses requisitos no arquivo de manifesto da seguinte forma:

        Assim, dispositivos que não tenham câmera e tenham versão Android anterior a 2.1 não poderão instalar o aplicativo a partir do Google Play.

        -

        No entanto, também é possível declarar que o aplicativo usa a câmera como recurso +

        No entanto, também é possível declarar que o aplicativo usa a câmera como recurso não obrigatório. Nesse caso, o aplicativo precisa definir o atributo {@code required} como {@code "false"} e verificar em tempo de execução se o dispositivo tem câmera e desativar os recursos da câmera conforme o necessário.

        diff --git a/docs/html-intl/intl/pt-br/guide/components/index.jd b/docs/html-intl/intl/pt-br/guide/components/index.jd index 02fcaa63c63a7..5131ead2239c3 100644 --- a/docs/html-intl/intl/pt-br/guide/components/index.jd +++ b/docs/html-intl/intl/pt-br/guide/components/index.jd @@ -1,7 +1,7 @@ page.title=Componentes do aplicativo page.landing=true -page.landing.intro=A estrutura de aplicativo do Android permite criar aplicativos ricos e inovadores usando um conjunto de componentes reutilizáveis. Esta seção explica como criar os componentes que definem os blocos de construção do aplicativo e como conectá-los usando intenções. -page.metaDescription=A estrutura de aplicativo do Android permite criar aplicativos ricos e inovadores usando um conjunto de componentes reutilizáveis. Esta seção mostra como criar os componentes que definem os blocos de construção do aplicativo e como conectá-los usando intenções. +page.landing.intro=A estrutura de aplicativo do Android permite criar aplicativos ricos e inovadores usando um conjunto de componentes reutilizáveis. Esta seção explica como criar os componentes que definem os blocos de construção do aplicativo e como conectá-los usando intenções. +page.metaDescription=A estrutura de aplicativo do Android permite criar aplicativos ricos e inovadores usando um conjunto de componentes reutilizáveis. Esta seção mostra como criar os componentes que definem os blocos de construção do aplicativo e como conectá-los usando intenções. page.landing.image=images/develop/app_components.png page.image=images/develop/app_components.png @@ -11,7 +11,7 @@ page.image=images/develop/app_components.png

        Artigos de blogue

        - +

        Uso de DialogFragments

        Nesta publicação, mostrarei como usar DialogFragments com a biblioteca de suporte v4 (para compatibilidade retroativa em dispositivos anteriores a Honeycomb) para mostrar uma caixa de diálogo de edição simples e retornar um resultado para a Atividade chamadora usando uma interface.

        @@ -21,7 +21,7 @@ page.image=images/develop/app_components.png

        Fragmentos para todos

        Hoje, lançamos uma biblioteca estática que expõe a mesma API Fragments (bem como o novo LoaderManager e algumas outras classes) para que aplicativos compatíveis com Android 1.6 e posteriores possam usar fragmentos para criar interfaces de usuário compatíveis com tablets.

        - +

        Multiencadeamento para desempenho

        Uma boa prática para criar aplicativos responsivos é garantir que o encadeamento principal da IU @@ -32,11 +32,11 @@ em um encadeamento diferente.

        Treinamento

        - +

        Gerenciamento do ciclo de vida da atividade

        Essa lição explica a importância dos métodos de retorno de chamada do ciclo de vida que cada instância de -Atividade recebe e como utilizá-los para que a atividade faça o que o usuário espera e não consuma recursos +Atividade recebe e como utilizá-los para que a atividade faça o que o usuário espera e não consuma recursos do sistema quando não estiver em uso.

        diff --git a/docs/html-intl/intl/pt-br/guide/components/loaders.jd b/docs/html-intl/intl/pt-br/guide/components/loaders.jd index f3c42094729db..c69cbbfd25d2c 100644 --- a/docs/html-intl/intl/pt-br/guide/components/loaders.jd +++ b/docs/html-intl/intl/pt-br/guide/components/loaders.jd @@ -21,14 +21,14 @@ parent.link=activities.html
      - +

      Classes principais

      1. {@link android.app.LoaderManager}
      2. {@link android.content.Loader}
      3. -
      - + +

      Exemplos relacionados

      1. @@ -51,7 +51,7 @@ quando o conteúdo é alterado.
      2. quando são recriados após uma alteração de configuração. Portanto, eles não precisam reconsultar os dados.
    - +

    Resumo da API de carregador

    Há várias classes e interfaces que podem ser envolvidas no uso @@ -68,7 +68,7 @@ de carregadores em um aplicativo. Elas são resumidas nesta tabela:

    {@link android.app.Fragment} para gerenciar uma ou mais instâncias de {@link android.content.Loader}. Isto ajuda um aplicativo a gerenciar operações executadas por longos períodos juntamente com o ciclo de vida de {@link android.app.Activity} -ou {@link android.app.Fragment}; o uso mais comum disto é com +ou {@link android.app.Fragment}; o uso mais comum disto é com {@link android.content.CursorLoader}. No entanto, os aplicativos têm a liberdade de criar os próprios carregadores para outros tipos de dados.
    @@ -129,7 +129,7 @@ de {@link android.content.Loader} ou {@link android.content.AsyncTaskLoader} para carregar dados de outra origem.
  • Uma implementação de {@link android.app.LoaderManager.LoaderCallbacks}. É aqui que é possível criar novos carregadores e gerenciar as referências -a carregadores existentes.
  • +a carregadores existentes.
  • Uma maneira de exibir os dados do carregador, como um {@link android.widget.SimpleCursorAdapter}.
  • Uma origem de dados, como um {@link android.content.ContentProvider}, ao usar @@ -140,7 +140,7 @@ android.widget.SimpleCursorAdapter}.
  • O {@link android.app.LoaderManager} gerencia uma ou mais instâncias de {@link android.content.Loader} dentro de uma {@link android.app.Activity} ou um {@link android.app.Fragment}. Há apenas um {@link -android.app.LoaderManager} por atividade ou fragmento.

    +android.app.LoaderManager} por atividade ou fragmento.

    Geralmente, inicializa-se um {@link android.content.Loader} dentro do método {@link @@ -157,13 +157,13 @@ recebe os seguintes parâmetros:

    • Um ID único que identifica o carregador. Neste exemplo, o ID é 0.
    • Argumentos opcionais para fornecer ao carregador -em construção (null neste exemplo).
    • +em construção (null neste exemplo).
    • Uma implementação de {@link android.app.LoaderManager.LoaderCallbacks}, que {@link android.app.LoaderManager} chama para relatar eventos do carregador. Nesse exemplo,  a classe local implementa a interface de {@link android.app.LoaderManager.LoaderCallbacks}, para que ela passe uma referência -para si, {@code this}.
    • +para si, {@code this}.

    A chamada de {@link android.app.LoaderManager#initLoader initLoader()} garante que o carregador foi inicializado e que está ativo. Ela possui dois possíveis resultados:

    @@ -193,7 +193,7 @@ a vida do carregador automaticamente. O {@link android.app.LoaderManager} inicia e interrompe o carregamento quando necessário, além de manter o estado do carregador e do conteúdo associado. À medida que isso ocorre, você raramente interage com os carregadores diretamente (para ver um exemplo de métodos para aprimorar o comportamento -de um carregador, consulte o exemplo de
    LoaderThrottle). +de um carregador, consulte o exemplo de LoaderThrottle). Geralmente, usam-se os métodos {@link android.app.LoaderManager.LoaderCallbacks} para intervir no processo de carregamento quando determinados eventos ocorrem. Para obter mais informações sobre este assunto, consulte Uso dos retornos de chamada de LoaderManager.

    @@ -245,7 +245,7 @@ instancia e retorna um novo {@link android.content.Loader} para o ID fornecido. — chamado quando um carregador anteriormente criado termina o seu carregamento.
      -
    • {@link android.app.LoaderManager.LoaderCallbacks#onLoaderReset onLoaderReset()} +
    • {@link android.app.LoaderManager.LoaderCallbacks#onLoaderReset onLoaderReset()} — chamado quando um carregador anteriormente criado é reiniciado, tornando os dados indisponíveis.
    • @@ -343,7 +343,7 @@ public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

      Este método é chamado quando um carregador anteriormente criado é reiniciado, tornando os dados indisponíveis. Este retorno de chamada permite que você descubra quando os dados estão prestes a serem liberados para que seja possível remover a referência a eles.  

      -

      Esta implementação chama +

      Esta implementação chama {@link android.widget.SimpleCursorAdapter#swapCursor swapCursor()} com um valor de null:

      @@ -366,7 +366,7 @@ public void onLoaderReset(Loader<Cursor> loader) { android.app.Fragment} que exibe uma {@link android.widget.ListView} contendo os resultados de uma consulta aos provedores de conteúdo de contatos. Ela usa um {@link android.content.CursorLoader} para gerenciar a consulta no provedor.

      - +

      Para um aplicativo acessar os contatos de um usuário, como neste exemplo, o manifesto deverá incluir a permissão {@link android.Manifest.permission#READ_CONTACTS READ_CONTACTS}.

      diff --git a/docs/html-intl/intl/pt-br/guide/components/processes-and-threads.jd b/docs/html-intl/intl/pt-br/guide/components/processes-and-threads.jd index c8e636dacce83..9bd335d98e8fd 100644 --- a/docs/html-intl/intl/pt-br/guide/components/processes-and-threads.jd +++ b/docs/html-intl/intl/pt-br/guide/components/processes-and-threads.jd @@ -120,7 +120,7 @@ o dispositivo atingiu o estado de paginação de memória. Portanto, eliminar al
      • Se ele hospedar um {@link android.app.Activity} que não esteja em primeiro plano, -mas ainda seja visível para o usuário (o seu método {@link android.app.Activity#onPause onPause()} tiver sido chamado). +mas ainda seja visível para o usuário (o seu método {@link android.app.Activity#onPause onPause()} tiver sido chamado). Isto poderá ocorrer, por exemplo, se a atividade em primeiro plano iniciar um diálogo, o que permitirá que a atividade anterior seja vista por trás dela.
      • @@ -319,7 +319,7 @@ private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } - + /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { diff --git a/docs/html-intl/intl/pt-br/guide/components/recents.jd b/docs/html-intl/intl/pt-br/guide/components/recents.jd index 467f62067a546..9f7588593bba4 100644 --- a/docs/html-intl/intl/pt-br/guide/components/recents.jd +++ b/docs/html-intl/intl/pt-br/guide/components/recents.jd @@ -41,7 +41,7 @@ page.tags="recents","overview" atividades e tarefas acessadas recentemente. O usuário pode navegar pela lista e selecionar uma tarefa a retomar ou remover uma tarefa da lista deslizando-a para fora. Com a versão 5.0 do Android (API de nível 21), várias instâncias da -mesma atividade contendo diferentes documentos podem aparecer como tarefas na tela de visão geral. Por exemplo, o +mesma atividade contendo diferentes documentos podem aparecer como tarefas na tela de visão geral. Por exemplo, o Google Drive pode ter uma tarefa para cada um dos vários documentos do Google. Cada documento aparece como uma tarefa na tela de visão geral.

        @@ -158,8 +158,8 @@ efeitos quando o usuário abre um documento com o aplicativo:

        "{@code intoExisting}"
        A atividade reutiliza uma tarefa existente para o documento. Isso é o mesmo que configurar o - sinalizador {@link android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT} sem configurar - o sinalizador {@link android.content.Intent#FLAG_ACTIVITY_MULTIPLE_TASK}, como descrito em + sinalizador {@link android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT} sem configurar + o sinalizador {@link android.content.Intent#FLAG_ACTIVITY_MULTIPLE_TASK}, como descrito em Uso do sinalizador Intent para adicionar uma tarefa acima.
        "{@code always}"
        @@ -169,7 +169,7 @@ efeitos quando o usuário abre um documento com o aplicativo:

        "{@code none”}"
        A atividade não cria uma nova tarefa para o documento. A tela de visão geral trata a - atividade como aconteceria por padrão: ela exibe uma tarefa para o aplicativo, que + atividade como aconteceria por padrão: ela exibe uma tarefa para o aplicativo, que retoma a atividade invocada por último pelo usuário.
        "{@code never}"
        @@ -205,7 +205,7 @@ recentemente é removida da tela de visão geral. O valor máximo de {@code andr

        Uso da classe AppTask para remover tarefas

        -

        Na atividade que cria uma nova tarefa na tela de visão geral, é possível +

        Na atividade que cria uma nova tarefa na tela de visão geral, é possível especificar quando remover a tarefa e terminar todas as atividades associadas a ela chamando o método {@link android.app.ActivityManager.AppTask#finishAndRemoveTask() finishAndRemoveTask()}.

        diff --git a/docs/html-intl/intl/pt-br/guide/components/services.jd b/docs/html-intl/intl/pt-br/guide/components/services.jd index 123d90ac9cb32..564ac80d3506c 100644 --- a/docs/html-intl/intl/pt-br/guide/components/services.jd +++ b/docs/html-intl/intl/pt-br/guide/components/services.jd @@ -185,7 +185,7 @@ usá-los a partir de outros componentes do aplicativo.

        Como atividades (e outros componentes), você deve declarar todos os serviços no arquivo de manifesto do aplicativo.

        -

        Para declarar o serviço, adicione um elemento {@code <service>} +

        Para declarar o serviço, adicione um elemento {@code <service>} como filho do elemento {@code <application>} . Por exemplo:

        @@ -494,7 +494,7 @@ a cada constante.

        Início de um serviço

        -

        É possível iniciar um dispositivo de uma atividade ou outro componente do aplicativo passando uma +

        É possível iniciar um dispositivo de uma atividade ou outro componente do aplicativo passando uma {@link android.content.Intent} a {@link android.content.Context#startService startService()}. O sistema Android chama o método {@link android.app.Service#onStartCommand onStartCommand()} do serviço e passa a ele a {@link diff --git a/docs/html-intl/intl/pt-br/guide/components/tasks-and-back-stack.jd b/docs/html-intl/intl/pt-br/guide/components/tasks-and-back-stack.jd index d309c6704f376..8e485b0fc939d 100644 --- a/docs/html-intl/intl/pt-br/guide/components/tasks-and-back-stack.jd +++ b/docs/html-intl/intl/pt-br/guide/components/tasks-and-back-stack.jd @@ -77,7 +77,7 @@ android.app.Fragment} class documentation.

        --> -

        A tela inicial do dispositivo é o ponto de partida para a maioria das tarefas. Quando o usuário toca em um ícone no inicializador do +

        A tela inicial do dispositivo é o ponto de partida para a maioria das tarefas. Quando o usuário toca em um ícone no inicializador do aplicativo (ou em um atalho na tela inicial), essa tarefa do aplicativo acontece em primeiro plano. Se não existir nenhuma tarefa para o aplicativo (se o aplicativo não tiver sido usado recentemente), uma nova tarefa @@ -85,7 +85,7 @@ será criada e a atividade "principal" daquele aplicativo abrirá como a ativida

        Quando a atividade atual inicia outra, a nova atividade é colocada no topo da pilha e recebe foco. A atividade anterior permanece na pilha, mas é interrompida. Quando uma atividade -para, o sistema retém o estado atual da interface do usuário. Quando o usuário pressiona o botão +para, o sistema retém o estado atual da interface do usuário. Quando o usuário pressiona o botão Voltar , a atividade atual é retirada do topo da pilha (a atividade é destruída) e a atividade anterior reinicia (o estado anterior da IU é restaurado). Atividades na pilha nunca @@ -103,7 +103,7 @@ a atividade atual é destruída e a atividade anterior reinicia.

        -

        Se o usuário continua pressionando Voltar, cada atividade na pilha é retirada para +

        Se o usuário continua pressionando Voltar, cada atividade na pilha é retirada para revelar a anterior até que o usuário retorne à tela inicial (ou a qualquer atividade que estivesse em execução no começo da tarefa). Quando todas as atividades forem removidas da pilha, a tarefa não existirá mais.

        @@ -295,7 +295,7 @@ launchMode} do elemento

        O atributo {@code launchMode} especifica uma instrução sobre como a atividade deve ser inicializada -em uma tarefa. Há quatro modos diferentes de inicialização que podem ser designados ao atributo +em uma tarefa. Há quatro modos diferentes de inicialização que podem ser designados ao atributo launchMode:

        @@ -334,7 +334,7 @@ Entretanto, se uma instância da atividade já existir em uma tarefa separada, o a intenção àquela instância por meio de uma chamada do método {@link android.app.Activity#onNewIntent onNewIntent()} em vez de criar uma nova instância. Somente uma instância da atividade pode existir por vez. -

        Observação: embora a atividade inicie em uma nova tarefa, o botão +

        Observação: embora a atividade inicie em uma nova tarefa, o botão Voltar ainda direciona o usuário à atividade anterior.

    {@code "singleInstance"}.
    Igual à {@code "singleTask"}, exceto que o sistema não inicializa nenhuma outra atividade @@ -505,7 +505,7 @@ A tarefa reterá todas as atividades em sua pilha mesmo após um longo período. href="{@docRoot}guide/topics/manifest/activity-element.html#clear">clearTaskOnLaunch
    Se esse atributo for definido como {@code "true"} na atividade raiz de uma tarefa, a pilha será apagada da atividade raiz sempre que o usuário sair da tarefa -e retornar a ela. Em outras palavras, é o oposto de +e retornar a ela. Em outras palavras, é o oposto de {@code alwaysRetainTaskState}. O usuário sempre retorna à tarefa no estado inicial, mesmo ao retirar-se da tarefa somente por um momento.
    @@ -557,13 +557,13 @@ nova tarefa, e o usuário perderia algum tempo trabalhando nessa tarefa. O usuá Página inicial. A tarefa é enviada para segundo plano e não fica mais visível. O usuário não tem como voltar à tarefa porque ela não é representada no inicializador do aplicativo.

    -

    Para esses casos em que se deseja que o usuário não seja capaz de retornar a uma atividade, defina +

    Para esses casos em que se deseja que o usuário não seja capaz de retornar a uma atividade, defina {@code finishOnTaskLaunch} - do elemento + do elemento <activity> como {@code "true"} (consulte Apagar a pilha).

    -

    Veja mais informações sobre a representação e o gerenciamento de atividades +

    Veja mais informações sobre a representação e o gerenciamento de atividades na tela de visão geral em Tela de visão geral.

    diff --git a/docs/html-intl/intl/pt-br/guide/index.jd b/docs/html-intl/intl/pt-br/guide/index.jd index ab396477e2506..74151ccd26ba6 100644 --- a/docs/html-intl/intl/pt-br/guide/index.jd +++ b/docs/html-intl/intl/pt-br/guide/index.jd @@ -29,7 +29,7 @@ tela para a interface de usuário e um serviço realiza trabalho em segundo plano de forma independente.

    De um componente, é possível executar outro componente usando uma intenção. É possível até mesmo -iniciar um componente em um aplicativo diferente, como uma atividade em um aplicativo de mapas para mostrar um endereço. Esse modelo +iniciar um componente em um aplicativo diferente, como uma atividade em um aplicativo de mapas para mostrar um endereço. Esse modelo fornece vários pontos de entrada para um único aplicativo e permite que qualquer aplicativo se comporte como o "padrão" de um usuário para uma ação que outros aplicativos podem invocar.

    @@ -53,7 +53,7 @@ diferentes configurações de dispositivos. Por exemplo, é possível criar dife de layout para diversos tamanhos de tela e o sistema determina qual layout deverá aplicar com base no tamanho da tela do dispositivo atual.

    -

    Você pode consultar a disponibilidade dos recursos do dispositivo em tempo de execução se qualquer recurso do +

    Você pode consultar a disponibilidade dos recursos do dispositivo em tempo de execução se qualquer recurso do aplicativo exigir hardware específico, como uma câmera. Se necessário, também é possível declarar recursos que o aplicativo exige, para que mercados como a Google Play Store não permitam a instalação em dispositivos que não sejam compatíveis com aquele recurso.

    diff --git a/docs/html-intl/intl/pt-br/guide/topics/manifest/manifest-intro.jd b/docs/html-intl/intl/pt-br/guide/topics/manifest/manifest-intro.jd index e33779684a5c0..639b6dbf4bf13 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/manifest/manifest-intro.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/manifest/manifest-intro.jd @@ -34,14 +34,14 @@ O nome do pacote serve como identificador exclusivo para o aplicativo.
  • Descrever os componentes do aplicativo — as atividades, os serviços, os receptores de transmissão e os provedores de conteúdo que compõem o aplicativo. Nomear as classes que implementam os componentes -e publicam seus recursos (por exemplo, que mensagens {@link android.content.Intent +e publicam seus recursos (por exemplo, que mensagens {@link android.content.Intent Intent} eles podem tratar). Essas declarações permitem ao sistema Android saber quais são os componentes e em que condições eles podem ser iniciados.
  • -
  • Determinar que processos hospedarão componentes de aplicativo.
  • +
  • Determinar que processos hospedarão componentes de aplicativo.
  • Declarar as permissões que o aplicativo deve ter para acessar -partes protegidas da API e interagir com outros aplicativos.
  • +partes protegidas da API e interagir com outros aplicativos.
  • Declarar também as permissões que outros devem ter para interagir com os componentes do aplicativo.
  • @@ -66,7 +66,7 @@ elemento que ele pode conter. Cada elemento e seus atributos são documentados na totalidade em um arquivo separado. Para exibir informações detalhadas sobre cada elemento, clique no nome do elemento no diagrama, na lista de elementos em ordem alfabética que acompanha o diagrama -ou em qualquer outra menção ao nome do elemento. +ou em qualquer outra menção ao nome do elemento.

    @@ -128,7 +128,7 @@ ou em qualquer outra menção ao nome do elemento.
     

    Todos os elementos que podem aparecer no arquivo de manifesto estão relacionados abaixo em ordem alfabética. Estes são os únicos elementos legais. Não é possível -adicionar elementos ou atributos próprios. +adicionar elementos ou atributos próprios.

    @@ -158,7 +158,7 @@ adicionar elementos ou atributos próprios.

    - +

    Convenções de arquivos

    @@ -172,25 +172,25 @@ no manifesto:
    Somente os elementos <manifest> e <application> -são necessários — eles devem estar presentes e ocorrer somente uma vez. +são necessários — eles devem estar presentes e ocorrer somente uma vez. A maioria dos outros pode ocorrer diversas vezes ou nunca — embora pelo menos alguns deles devam estar presentes para que o manifesto realize algo significativo.

    -Se um elemento contiver qualquer coisa, ele conterá outros elementos. +Se um elemento contiver qualquer coisa, ele conterá outros elementos. Todos os valores são definidos por meio de atributos, e não como dados de caracteres dentro de um elemento.

    Elementos de mesmo nível geralmente não são ordenados. Por exemplo: os elementos -<activity>, +<activity>, <provider> -e <service> -podem ser combinados entre si em qualquer sequência. (O elemento +e <service> +podem ser combinados entre si em qualquer sequência. (O elemento <activity-alias> -é uma exceção a essa regra: ele deve seguir o -<activity> +é uma exceção a essa regra: ele deve seguir o +<activity> para o qual é alias.)

    @@ -200,32 +200,32 @@ devem ser especificados para um elemento para cumprir a sua finalidade. Use a documentação como guia. Para atributos verdadeiramente opcionais, ele menciona um valor padrão ou declara o que acontece na ausência de uma especificação. -

    Exceto por alguns atributos do elemento +

    Exceto por alguns atributos do elemento <manifest> -raiz, todos os nomes de atributo têm um prefixo {@code android:} — +raiz, todos os nomes de atributo têm um prefixo {@code android:} — por exemplo, {@code android:alwaysRetainTaskState}. Como o prefixo é universal, a documentação geralmente o omite ao referir-se a atributos pelo nome.

    Declaração de nomes de classe
    Muitos elementos correspondem a objetos Java, inclusive elementos do próprio -aplicativo (o elemento -<application> -) e seus componentes principais — atividades -(<activity>), -serviços -(<service>), -receptores de transmissão -(<receiver>) -e provedores de conteúdo -(<provider>). +aplicativo (o elemento +<application> +) e seus componentes principais — atividades +(<activity>), +serviços +(<service>), +receptores de transmissão +(<receiver>) +e provedores de conteúdo +(<provider>).

    -Se uma subclasse for definida, como quase sempre acontece para classes de componentes -({@link android.app.Activity}, {@link android.app.Service}, -{@link android.content.BroadcastReceiver} e {@link android.content.ContentProvider}), +Se uma subclasse for definida, como quase sempre acontece para classes de componentes +({@link android.app.Activity}, {@link android.app.Service}, +{@link android.content.BroadcastReceiver} e {@link android.content.ContentProvider}), a subclasse será declarada por meio de um atributo {@code name}. O nome deve conter -toda a designação do pacote. +toda a designação do pacote. Por exemplo: uma subclasse {@link android.app.Service} pode ser declarada assim:

    @@ -240,11 +240,11 @@ Por exemplo: uma subclasse {@link android.app.Service} pode ser declarada assim:

    No entanto, para encurtar, se o primeiro caractere da string for um ponto, -a string será acrescentada ao nome do pacote do aplicativo (conforme especificado pelo atributo -package - do elemento -<manifest> -). A seguinte atribuição é igual à atribuição acima: +a string será acrescentada ao nome do pacote do aplicativo (conforme especificado pelo atributo +package + do elemento +<manifest> +). A seguinte atribuição é igual à atribuição acima:

    <manifest package="com.example.project" . . . >
    @@ -257,13 +257,13 @@ a string será acrescentada ao nome do pacote do aplicativo (conforme especifica
     </manifest>

    -Ao iniciar um componente, o Android cria uma instância da subclasse nomeada. +Ao iniciar um componente, o Android cria uma instância da subclasse nomeada. Se nenhuma subclasse for especificada, ele criará uma instância da classe base.

    Vários valores
    Se for especificado mais de um valor, o elemento sempre será repetido -em vez de listar os vários valores dentro de um único elemento. +em vez de listar os vários valores dentro de um único elemento. Por exemplo, um filtro de intenção pode listar algumas ações:
    <intent-filter . . . >
    @@ -276,22 +276,22 @@ Por exemplo, um filtro de intenção pode listar algumas ações:
     
    Valores de recurso
    Alguns atributos têm valores que podem ser exibidos aos usuários — por exemplo, uma etiqueta e um ícone de uma atividade. Os valores desses atributos -devem ser localizados e, por tanto, definidos a partir de um recurso ou tema. Os valores +devem ser localizados e, por tanto, definidos a partir de um recurso ou tema. Os valores de recurso são expressos no formato a seguir:

    {@code @[pacote:]tipo:nome}

    em que o nome do pacote pode ser omitido se o recurso estiver no mesmo pacote -que o aplicativo tipo é um tipo de recurso — como uma "string" ou -"drawable" (desenhável) — e nome é o nome que identifica o recurso específico. +que o aplicativo tipo é um tipo de recurso — como uma "string" ou +"drawable" (desenhável) — e nome é o nome que identifica o recurso específico. Por exemplo:

    <activity android:icon="@drawable/smallPic" . . . >

    -Os valores de um tema são expressos de forma semelhante, mas, com um '{@code ?}' +Os valores de um tema são expressos de forma semelhante, mas, com um '{@code ?}' em vez de '{@code @}':

    @@ -299,8 +299,8 @@ em vez de '{@code @}':

    Valores de string
    -
    Quando o valor de um atributo é uma string, devem-se usar duas barras invertidas ('{@code \\}') -para caracteres de escape — por exemplo, '{@code \\n}' para +
    Quando o valor de um atributo é uma string, devem-se usar duas barras invertidas ('{@code \\}') +para caracteres de escape — por exemplo, '{@code \\n}' para uma nova linha ou '{@code \\uxxxx}' para um caractere Unicode.
    @@ -320,7 +320,7 @@ Os componentes fundamentais de um aplicativo (suas atividades, serviços e recep de transmissão) são ativados por intenções. Intenções são pacotes de informações (objetos {@link android.content.Intent}) que descrevem uma ação desejada — inclusive os dados usados em ações, a categoria -do componente que deve executar a ação e outras instruções pertinentes. +do componente que deve executar a ação e outras instruções pertinentes. O Android localiza um componente adequado para responder à intenção, inicia uma nova instância do componente se necessário e passa-o ao objeto da intenção. @@ -330,7 +330,7 @@ ao objeto da intenção. Os componentes anunciam seus recursos — os tipos de intenção aos quais eles podem responder — por meio de filtros de intenções. Como o sistema Android precisa saber que intenções um componente pode tratar antes de iniciá-lo, os filtros -de intenções são especificados no manifesto como elementos +de intenções são especificados no manifesto como elementos <intent-filter> . Os componentes podem ter qualquer quantidade de filtros, em que cada um descreve um recurso diferente. @@ -345,8 +345,8 @@ do componente.

    Para ver como os objetos de intenção são testados em relação aos filtros de intenções, -consulte o documento -Intenções +consulte o documento +Intenções e filtros de intenções em separado.

    @@ -355,41 +355,41 @@ e filtros de intenções em separado.

    Alguns elementos têm atributos {@code icon} e {@code label} de um pequeno ícone -e uma etiqueta de texto que pode ficar visível para os usuários. Alguns deles também têm um atributo -{@code description} para um texto explicativo mais longo que também pode ser -exibido na tela. Por exemplo: o elemento +e uma etiqueta de texto que pode ficar visível para os usuários. Alguns deles também têm um atributo +{@code description} para um texto explicativo mais longo que também pode ser +exibido na tela. Por exemplo: o elemento <permission> -tem todos os três atributos; assim, quando o usuário é consultado para dar -permissão a um aplicativo que a solicitou, serão apresentados ao usuário um ícone -que representa a permissão, o nome da permissão e uma descrição +tem todos os três atributos; assim, quando o usuário é consultado para dar +permissão a um aplicativo que a solicitou, serão apresentados ao usuário um ícone +que representa a permissão, o nome da permissão e uma descrição de tudo o que está envolvido.

    -Em todo caso, o ícone e a etiqueta definidos em um elemento recipiente se tornam as configurações -{@code icon} e {@code label} padrão de todos os subelementos do contêiner. -Assim, o ícone e a etiqueta definidos no elemento -<application> -são o ícone e a etiqueta padrão para cada um dos componentes do aplicativo. -Da mesma forma, o ícone e a etiqueta definidos para um componente — por exemplo, um elemento -<activity> - — são as configurações padrão para cada um dos elementos -<intent-filter> +Em todo caso, o ícone e a etiqueta definidos em um elemento recipiente se tornam as configurações +{@code icon} e {@code label} padrão de todos os subelementos do contêiner. +Assim, o ícone e a etiqueta definidos no elemento +<application> +são o ícone e a etiqueta padrão para cada um dos componentes do aplicativo. +Da mesma forma, o ícone e a etiqueta definidos para um componente — por exemplo, um elemento +<activity> + — são as configurações padrão para cada um dos elementos +<intent-filter> do componente. Se um elemento -<application> -define uma etiqueta, mas uma atividade e seu filtro de intenção não definem, -a etiqueta do aplicativo é tratada como a etiqueta de atividade +<application> +define uma etiqueta, mas uma atividade e seu filtro de intenção não definem, +a etiqueta do aplicativo é tratada como a etiqueta de atividade e do filtro de intenção.

    -O ícone e a etiqueta definidos para um filtro de intenção são usados para representar um componente +O ícone e a etiqueta definidos para um filtro de intenção são usados para representar um componente apresentado para o usuário para preencher a função -anunciada pelo filtro. Por exemplo: um filtro com as configurações -"{@code android.intent.action.MAIN}" e -"{@code android.intent.category.LAUNCHER}" anuncia uma atividade +anunciada pelo filtro. Por exemplo: um filtro com as configurações +"{@code android.intent.action.MAIN}" e +"{@code android.intent.category.LAUNCHER}" anuncia uma atividade como uma que inicia um aplicativo — ou seja, -que deve ser exibida no inicializador do aplicativo. O ícone e a etiqueta +que deve ser exibida no inicializador do aplicativo. O ícone e a etiqueta definidos no filtro são, portanto, as exibidas no inicializador.

    @@ -397,14 +397,14 @@ definidos no filtro são, portanto, as exibidas no inicializador.

    Permissões

    -As permissões são restrições que limitam o acesso a parte do código -ou aos dados de um dispositivo. A limitação é imposta para proteger dados -essenciais que podem sofrer mau uso e distorções ou prejudicar a experiência do usuário. +As permissões são restrições que limitam o acesso a parte do código +ou aos dados de um dispositivo. A limitação é imposta para proteger dados +essenciais que podem sofrer mau uso e distorções ou prejudicar a experiência do usuário.

    -Cada permissão é identificada por uma etiqueta exclusiva. Geralmente a etiqueta indica -a ação que foi restringida. A seguir há alguns exemplos de permissões definidas +Cada permissão é identificada por uma etiqueta exclusiva. Geralmente a etiqueta indica +a ação que foi restringida. A seguir há alguns exemplos de permissões definidas pelo Android:

    @@ -418,25 +418,25 @@ Um recurso pode ser protegido por, no máximo, uma permissão.

    -Se um aplicativo precisar de acesso a um recurso protegido por uma permissão, -ele deve declarar que precisa da permissão com um elemento -<uses-permission> -no manifesto. Assim, quando o aplicativo é instalado -no dispositivo, o instalador determina se concederá ou não a permissão -solicitada, marcando as autoridades que assinaram os certificados -do aplicativo e, em alguns casos, perguntando ao usuário. -Se a permissão for concedida, o aplicativo será capaz de usar os recursos -protegidos. Caso contrário, sua tentativa de acessar esses recursos simplesmente falhará -sem nenhuma notificação ao usuário. +Se um aplicativo precisar de acesso a um recurso protegido por uma permissão, +ele deve declarar que precisa da permissão com um elemento +<uses-permission> +no manifesto. Assim, quando o aplicativo é instalado +no dispositivo, o instalador determina se concederá ou não a permissão +solicitada, marcando as autoridades que assinaram os certificados +do aplicativo e, em alguns casos, perguntando ao usuário. +Se a permissão for concedida, o aplicativo será capaz de usar os recursos +protegidos. Caso contrário, sua tentativa de acessar esses recursos simplesmente falhará +sem nenhuma notificação ao usuário.

    -Um aplicativo também pode proteger seus componentes (atividades, serviços, -receptores de transmissão e provedores de conteúdo) com permissões. Ele pode empregar -qualquer uma das permissões definidas pelo Android (listadas em -{@link android.Manifest.permission android.Manifest.permission}) ou declaradas -por outros aplicativos. Ou então, ele pode definir as suas próprias. As novas permissões são declaradas -com o elemento +Um aplicativo também pode proteger seus componentes (atividades, serviços, +receptores de transmissão e provedores de conteúdo) com permissões. Ele pode empregar +qualquer uma das permissões definidas pelo Android (listadas em +{@link android.Manifest.permission android.Manifest.permission}) ou declaradas +por outros aplicativos. Ou então, ele pode definir as suas próprias. As novas permissões são declaradas +com o elemento <permission>. Por exemplo: uma atividade pode ser protegida da seguinte forma:

    @@ -458,41 +458,41 @@ com o elemento

    Observe que, nesse exemplo, a permissão {@code DEBIT_ACCT}, além de declarada -com o elemento +com o elemento <permission> -, tem seu uso solicitado com o elemento +, tem seu uso solicitado com o elemento <uses-permission>. Ela deve ser solicitada para que outros componentes do aplicativo -iniciem a atividade protegida, mesmo que a proteção -seja imposta pelo próprio aplicativo. +iniciem a atividade protegida, mesmo que a proteção +seja imposta pelo próprio aplicativo.

    Se, no mesmo exemplo, o atributo {@code permission} fosse definido -como uma permissão declarada em outro lugar +como uma permissão declarada em outro lugar (como {@code android.permission.CALL_EMERGENCY_NUMBERS}), não seria -necessário declará-la novamente com um elemento +necessário declará-la novamente com um elemento <permission>. - No entanto, ainda seria necessário solicitar seu uso com -<uses-permission>. + No entanto, ainda seria necessário solicitar seu uso com +<uses-permission>.

    -O elemento -<permission-tree> -declara um espaço de nome de um grupo de permissões que será definido -no código. E +O elemento +<permission-tree> +declara um espaço de nome de um grupo de permissões que será definido +no código. E <permission-group> -define um etiqueta de um conjunto de permissões (os dois declarados no manifesto com elementos -<permission> -e as declaradas em outro lugar). Ele afeta somente a forma com que as permissões estão -agrupadas quando apresentadas ao usuário. O elemento +define um etiqueta de um conjunto de permissões (os dois declarados no manifesto com elementos +<permission> +e as declaradas em outro lugar). Ele afeta somente a forma com que as permissões estão +agrupadas quando apresentadas ao usuário. O elemento <permission-group> -não especifica que permissões pertencem ao grupo; +não especifica que permissões pertencem ao grupo; ele só dá um nome ao grupo. Para incluir uma permissão no grupo, -designa-se o nome do grupo ao atributo -permissionGroup - do elemento +designa-se o nome do grupo ao atributo +permissionGroup + do elemento <permission>.

    @@ -501,17 +501,17 @@ designa-se o nome do grupo ao atributo

    Bibliotecas

    -Todo aplicativo está vinculado à biblioteca Android padrão, que -contém os pacotes básicos para programar aplicativos (com classes comuns +Todo aplicativo está vinculado à biblioteca Android padrão, que +contém os pacotes básicos para programar aplicativos (com classes comuns tais como Activity, Service, Intent, View, Button, Application, ContentProvider etc.).

    -No entanto, alguns pacotes residem em suas próprias bibliotecas. Se o aplicativo -usar código de algum desses pacotes, ele deve receber solicitação explícita para ser -vinculado a eles. O manifesto deve conter um elemento +No entanto, alguns pacotes residem em suas próprias bibliotecas. Se o aplicativo +usar código de algum desses pacotes, ele deve receber solicitação explícita para ser +vinculado a eles. O manifesto deve conter um elemento <uses-library> - separado para nomear cada uma das bibliotecas (o nome da biblioteca se encontra + separado para nomear cada uma das bibliotecas (o nome da biblioteca se encontra na documentação do pacote).

    diff --git a/docs/html-intl/intl/pt-br/guide/topics/providers/calendar-provider.jd b/docs/html-intl/intl/pt-br/guide/topics/providers/calendar-provider.jd index ce72b7db5cff0..42a517b73783f 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/providers/calendar-provider.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/providers/calendar-provider.jd @@ -42,7 +42,7 @@ page.title=Provedor de agenda
  • Uso de intenções para exibir dados de agenda
  • - +
  • Adaptadores de sincronização
  • @@ -113,26 +113,26 @@ as tabelas e os campos principais que as vinculam entre si.

    {@link android.provider.CalendarContract.Calendars}

    - + Essa tabela contém as informações específicas da agenda. Cada linha nessa tabela contém os detalhes de uma única agenda, como nome, cor, informações de sincronização etc. {@link android.provider.CalendarContract.Events} - + Essa tabela contém as informações específicas do evento. Cada linha nessa tabela tem as informações de um único evento — por exemplo: título do evento, local, horário de início, horário de término etc. O evento pode ocorrer uma vez ou diversas vezes. Os participantes, -lembretes e propriedades estendidas são armazenados em tabelas separadas. +lembretes e propriedades estendidas são armazenados em tabelas separadas. Cada um deles tem um {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} que referencia o {@link android.provider.BaseColumns#_ID} na tabela de eventos. {@link android.provider.CalendarContract.Instances} - + Essa tabela contém os horários de início e término para cada ocorrência em um evento. Cada linha nessa tabela representa uma única ocorrência do evento. Para eventos de ocorrência única, há um mapeamento 1:1 @@ -141,7 +141,7 @@ a diversas ocorrências daquele evento são geradas automaticamente. {@link android.provider.CalendarContract.Attendees} - + Essa tabela contém as informações dos participantes (convidados) do evento. Cada linha representa um único convidado de um evento. Ela especifica o tipo de convidado e a resposta quanto à participação do convidado @@ -149,7 +149,7 @@ no evento. {@link android.provider.CalendarContract.Reminders} - + Essa tabela contém os dados de alerta/notificação. Cada linha representa um único alerta de um evento. Um evento pode ter vários lembretes. O número máximo de lembretes por evento @@ -159,7 +159,7 @@ que é definido pelo adaptador de sincronização que possui a agenda fornecida. Os lembretes são especificados em minutos antes do evento e têm um método que determina a forma de alertar o usuário. - +

    A API do Provedor de Agenda é projetada para ser flexível e poderosa. Ao mesmo tempo, @@ -211,7 +211,7 @@ para excluir, inserir ou atualizar dados da agenda:

    A tabela {@link android.provider.CalendarContract.Calendars} contém detalhes de agendas individuais. As colunas -Agendas a seguir são graváveis tanto por aplicativos quanto por adaptadores de sincronização. +Agendas a seguir são graváveis tanto por aplicativos quanto por adaptadores de sincronização. Para obter uma lista completa de campos compatíveis, consulte a referência {@link android.provider.CalendarContract.Calendars}

    @@ -229,7 +229,7 @@ a referência {@link android.provider.CalendarContract.Calendars}

    - + - +

    A seguir há um exemplo que mostra como obter as agendas de propriedade de determinado usuário. Para simplificar o exemplo, a operação de consulta é exibida no encadeamento da interface do usuário ("encadeamento principal"). Na prática, isso deve ser feito em um encadeamento -assíncrono em vez de no encadeamento principal. Para ver mais discussões, consulte +assíncrono em vez de no encadeamento principal. Para ver mais discussões, consulte Carregadores. Se você não estiver somente lendo dados, mas modificando-os, consulte {@link android.content.AsyncQueryHandler}.

    @@ -268,13 +268,13 @@ public static final String[] EVENT_PROJECTION = new String[] { Calendars.CALENDAR_DISPLAY_NAME, // 2 Calendars.OWNER_ACCOUNT // 3 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1; private static final int PROJECTION_DISPLAY_NAME_INDEX = 2; private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3; - + +sincronizadas.

    Na próxima parte do exemplo, você construirá a consulta. A seleção @@ -308,38 +308,38 @@ consulte Prove

    // Run query
     Cursor cur = null;
     ContentResolver cr = getContentResolver();
    -Uri uri = Calendars.CONTENT_URI;   
    -String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" 
    +Uri uri = Calendars.CONTENT_URI;
    +String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND ("
                             + Calendars.ACCOUNT_TYPE + " = ?) AND ("
                             + Calendars.OWNER_ACCOUNT + " = ?))";
     String[] selectionArgs = new String[] {"sampleuser@gmail.com", "com.google",
    -        "sampleuser@gmail.com"}; 
    -// Submit the query and get a Cursor object back. 
    +        "sampleuser@gmail.com"};
    +// Submit the query and get a Cursor object back.
     cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);

    Essa próxima seção usa o cursor para avançar pelo conjunto de resultados. Ele usa as constantes definidas no início do exemplo para retornar os valores de cada campo.

    - +
    // Use the cursor to step through the returned records
     while (cur.moveToNext()) {
         long calID = 0;
         String displayName = null;
         String accountName = null;
         String ownerName = null;
    -      
    +
         // Get the field values
         calID = cur.getLong(PROJECTION_ID_INDEX);
         displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
         accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
         ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
    -              
    +
         // Do something with the values...
     
        ...
     }
     
    - +

    Modificação de uma agenda

    Para realizar uma atualização de uma agenda, é possível fornecer o {@link @@ -350,7 +350,7 @@ URI ou como o primeiro item de seleção. A seleção deve iniciar com "_id=?" e o primeiro selectionArg deve ser o {@link -android.provider.BaseColumns#_ID} da agenda. +android.provider.BaseColumns#_ID} da agenda. Também é possível realizar atualizações com codificações do ID na URI. Este exemplo altera o nome de exibição de uma agenda usando a abordagem @@ -377,14 +377,14 @@ android.provider.CalendarContract.SyncColumns#ACCOUNT_TYPE} de {@link android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL}. {@link android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL} é um tipo de conta especial para agendas -não associado a nenhuma conta do dispositivo. Agendas desse tipo não são sincronizadas com um servidor. Para +não associado a nenhuma conta do dispositivo. Agendas desse tipo não são sincronizadas com um servidor. Para ver discussões sobre adaptadores de sincronização, consulte Adaptadores de sincronização.

    Tabela de eventos

    A tabela {@link android.provider.CalendarContract.Events} contém detalhes de eventos individuais. Para adicionar, atualizar ou excluir eventos, um aplicativo deve -conter a permissão {@link android.Manifest.permission#WRITE_CALENDAR} +conter a permissão {@link android.Manifest.permission#WRITE_CALENDAR} no arquivo de manifesto.

    As colunas de Eventos a seguir são graváveis tanto por um aplicativo quanto por um adaptador @@ -434,7 +434,7 @@ android.provider.CalendarContract.Events}.

    - + - + - + - - + + - + - + - + - - + - + - + @@ -514,11 +514,11 @@ java.util.TimeZone#getAvailableIDs()}. Observe que essa regra não se aplica a inserções de evento pela intenção {@link android.content.Intent#ACTION_INSERT INSERT} descrita em Uso de uma intenção para inserir um evento — nesta situação, é fornecido um fuso horário padrão. - +
  • Para eventos não recorrentes, é preciso incluir {@link android.provider.CalendarContract.EventsColumns#DTEND}.
  • - - + +
  • Para eventos recorrentes, é necessário incluir uma {@link android.provider.CalendarContract.EventsColumns#DURATION} além de uma {@link android.provider.CalendarContract.EventsColumns#RRULE} ou {@link @@ -528,7 +528,7 @@ android.content.Intent#ACTION_INSERT INSERT} descrita em Tabela de participantes @@ -634,10 +634,10 @@ Log.i(DEBUG_TAG, "Rows deleted: " + rows); representa um único participante ou convidado de um evento. Chamar {@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} retorna uma lista de participantes para -o evento com o {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} dado. +o evento com o {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} dado. Esse {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} deve corresponder ao {@link -android.provider.BaseColumns#_ID} de determinado evento.

    +android.provider.BaseColumns#_ID} de determinado evento.

    A tabela a seguir lista os campos graváveis. Ao inserir um novo participante, é necessário incluir todos eles @@ -773,7 +773,7 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values);

    Tabela de instâncias

    -

    A tabela +

    A tabela {@link android.provider.CalendarContract.Instances} contém os horários de início e término das ocorrência de um evento. Cada linha nessa tabela representa uma única ocorrência do evento. A tabela de instâncias não é gravável e fornece @@ -782,7 +782,7 @@ somente um modo de consultar ocorrências de eventos.

    A tabela a seguir relaciona alguns dos campos passíveis de consulta de uma instância. Observe que o fuso horário é definido por {@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} -e +e {@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_INSTANCES}.

    @@ -801,18 +801,18 @@ e
  • - + - + - + @@ -820,16 +820,16 @@ no fuso horário do Agenda. - - + - +
    {@link android.provider.CalendarContract.Calendars#VISIBLE}Um booleano indicando se a agenda foi selecionada para ser exibida. Um valor de 0 indica que eventos associados a essa agenda não devem ser exibidos. Um valor de 1 indica que eventos associados a essa agenda devem @@ -240,7 +240,7 @@ android.provider.CalendarContract.Instances}.
    {@link android.provider.CalendarContract.CalendarColumns#SYNC_EVENTS}Um booleano que indica se a agenda deve ser sincronizada e ter os eventos armazenados no dispositivo. Um valor de 0 indica a não sincronização dessa agenda e o não armazenamento dos eventos no dispositivo. Um valor de 1 indica a sincronização dos eventos dessa agenda @@ -253,7 +253,7 @@ e o armazenamento dos eventos no dispositivo.
    {@link android.provider.CalendarContract.EventsColumns#DURATION}A duração do evento em formato RCF5545. Por exemplo, um valor de "PT1H" indica que o evento deve durar uma hora, e um valor de "P2W" indica @@ -444,39 +444,39 @@ uma duração de 2 semanas.
    {@link android.provider.CalendarContract.EventsColumns#ALL_DAY}Um valor de 1 indica que esse evento ocupa o dia inteiro, como definido pelo fuso horário local. Um valor de 0 indica que é um evento comum que pode iniciar e terminar a qualquer momento durante um dia.
    {@link android.provider.CalendarContract.EventsColumns#RRULE}A regra de recorrência do formato do evento. Por exemplo, "FREQ=WEEKLY;COUNT=10;WKST=SU". Veja mais exemplos aqui.
    {@link android.provider.CalendarContract.EventsColumns#RDATE}As datas de recorrência do evento. - Normalmente, usa-se {@link android.provider.CalendarContract.EventsColumns#RDATE} - em conjunto com {@link android.provider.CalendarContract.EventsColumns#RRULE} + As datas de recorrência do evento. + Normalmente, usa-se {@link android.provider.CalendarContract.EventsColumns#RDATE} + em conjunto com {@link android.provider.CalendarContract.EventsColumns#RRULE} para definir um conjunto agregado de ocorrências repetidas. Para ver mais discussões, consulte Especificação RFC5545.
    {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY}Se esse evento considera tempo ocupado ou se há tempo livre que pode ser reagendado.
    {@link android.provider.CalendarContract.EventsColumns#GUESTS_CAN_MODIFY}
    {@link android.provider.CalendarContract.Instances#END_DAY}O dia final juliano da instância relativo ao fuso horário -do Agenda. - +do Agenda. +
    {@link android.provider.CalendarContract.Instances#END_MINUTE}O minuto final da instância calculado a partir de meia-noite no fuso horário do Agenda.
    {@link android.provider.CalendarContract.Instances#EVENT_ID}
    {@link android.provider.CalendarContract.Instances#START_DAY}O dia inicial juliano da instância relativo ao fuso horário do Agenda. + O dia inicial juliano da instância relativo ao fuso horário do Agenda.
    {@link android.provider.CalendarContract.Instances#START_MINUTE}O minuto inicial da instância calculado a partir de meia-noite, relativo -ao fuso horário do Agenda. +ao fuso horário do Agenda.
    @@ -840,7 +840,7 @@ ao fuso horário do Agenda. na URI. Neste exemplo, {@link android.provider.CalendarContract.Instances} obtém acesso ao campo {@link android.provider.CalendarContract.EventsColumns#TITLE} por meio -da sua implementação da interface {@link android.provider.CalendarContract.EventsColumns}. +da sua implementação da interface {@link android.provider.CalendarContract.EventsColumns}. Em outras palavras, {@link android.provider.CalendarContract.EventsColumns#TITLE} é retornado por uma vista do banco de dados, não pela consulta da tabela {@link @@ -853,7 +853,7 @@ public static final String[] INSTANCE_PROJECTION = new String[] { Instances.BEGIN, // 1 Instances.TITLE // 2 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_BEGIN_INDEX = 1; @@ -868,7 +868,7 @@ long startMillis = beginTime.getTimeInMillis(); Calendar endTime = Calendar.getInstance(); endTime.set(2011, 10, 24, 8, 0); long endMillis = endTime.getTimeInMillis(); - + Cursor cur = null; ContentResolver cr = getContentResolver(); @@ -883,28 +883,28 @@ ContentUris.appendId(builder, startMillis); ContentUris.appendId(builder, endMillis); // Submit the query -cur = cr.query(builder.build(), - INSTANCE_PROJECTION, - selection, - selectionArgs, +cur = cr.query(builder.build(), + INSTANCE_PROJECTION, + selection, + selectionArgs, null); - + while (cur.moveToNext()) { String title = null; long eventID = 0; - long beginVal = 0; - + long beginVal = 0; + // Get the field values eventID = cur.getLong(PROJECTION_ID_INDEX); beginVal = cur.getLong(PROJECTION_BEGIN_INDEX); title = cur.getString(PROJECTION_TITLE_INDEX); - - // Do something with the values. - Log.i(DEBUG_TAG, "Event: " + title); + + // Do something with the values. + Log.i(DEBUG_TAG, "Event: " + title); Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(beginVal); + calendar.setTimeInMillis(beginVal); DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); - Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); + Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); } }
    @@ -923,8 +923,8 @@ while (cur.moveToNext()) { {@link android.content.Intent#ACTION_VIEW VIEW}

    content://com.android.calendar/time/<ms_since_epoch>

    Também pode-se consultar a URI com -{@link android.provider.CalendarContract#CONTENT_URI CalendarContract.CONTENT_URI}. -Para ver um exemplo do uso dessa intenção, consulte
    Uso de intenções para exibir dados de calendários. +{@link android.provider.CalendarContract#CONTENT_URI CalendarContract.CONTENT_URI}. +Para ver um exemplo do uso dessa intenção, consulte Uso de intenções para exibir dados de calendários. Abre a agenda no horário especificado por <ms_since_epoch>. @@ -935,11 +935,11 @@ Para ver um exemplo do uso dessa intenção, consulte Uso de intenções para exibir dados de calendários. - + Exibe o evento especificado por <event_id>. @@ -952,12 +952,12 @@ Para ver um exemplo do uso dessa intenção, consulte Uso de uma intenção para editar um evento. - - + + Edita o evento especificado por <event_id>. @@ -972,11 +972,11 @@ Para ver um exemplo do uso dessa intenção, consulte Uso de uma intenção para inserir um evento. - + Cria um evento. @@ -996,7 +996,7 @@ Para ver um exemplo do uso dessa intenção, consulte arquivo de manifesto.

    - +

    Quando usuários executam um aplicativo que usa essa abordagem, ele os direciona ao Agenda para finalizar a adição do evento. A intenção {@link android.content.Intent#ACTION_INSERT INSERT} usa campos extras para pré-preencher um formulário com os detalhes do evento na Agenda. Os usuários podem, então, cancelar o evento, editar o formulário conforme o necessário ou salvar o evento nas suas agendas.

    - +

    A seguir há um fragmento de código que agenda um evento em 19 de janeiro de 2012, que acontece @@ -1075,7 +1075,7 @@ das 7h30 às 8h30. Observe o exposto a seguir sobre esse fragmento de código:

  • Ele especifica {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} como a URI.
  • - +
  • Ele usa os campos extras {@link android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME} e {@link @@ -1083,10 +1083,10 @@ android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME} para pré-preencher o formulário com o horário do evento. Os valores desses horários devem estar em milissegundos UTC da época.
  • - +
  • Ele usa o campo extra {@link android.content.Intent#EXTRA_EMAIL Intent.EXTRA_EMAIL} para fornecer uma lista de termos separados por vírgula de convidados, especificados por endereço de e-mail.
  • - +
     Calendar beginTime = Calendar.getInstance();
    @@ -1158,12 +1158,12 @@ via aplicativo e via adaptador de sincronização:

    • Um adaptador de sincronização precisa especificar que é um adaptador de sincronização que define {@link android.provider.CalendarContract#CALLER_IS_SYNCADAPTER} como true.
    • - - + +
    • Os adaptadores de sincronização precisam fornecer um {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_NAME} e um {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_TYPE} como parâmetros da consulta na URI.
    • - +
    • Os adaptadores de sincronização têm acesso de gravação a mais colunas do que um aplicativo ou widget. Por exemplo: um aplicativo só pode modificar algumas características de uma agenda, como nome, nome de exibição, configurações de visibilidade e se a agenda está @@ -1180,5 +1180,5 @@ e ao ACCOUNT_TYPE que especificou.
    .appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build(); }
    -

    Para obter uma implementação de exemplo de um adaptador de sincronização (não especificamente relacionada ao Agenda), consulte +

    Para obter uma implementação de exemplo de um adaptador de sincronização (não especificamente relacionada ao Agenda), consulte SampleSyncAdapter. diff --git a/docs/html-intl/intl/pt-br/guide/topics/providers/contacts-provider.jd b/docs/html-intl/intl/pt-br/guide/topics/providers/contacts-provider.jd index 0d42d2daed530..f3b7c58523af7 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/providers/contacts-provider.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/providers/contacts-provider.jd @@ -113,14 +113,14 @@ o Provedor de Contatos. Este guia considera que o leitor conhece os preceitos dos provedores de conteúdo do Android. Para saber mais sobre provedores de conteúdo do Android, leia o guia - Preceitos do provedor de conteúdo. + Preceitos do provedor de conteúdo. O aplicativo Exemplo de adaptador de sincronização é um exemplo de uso de um adaptador de sincronização que transfere dados entre o Provedor de contatos e um aplicativo de amostra hospedado pelo Google Web Services.

    Organização do Provedor de Contatos

    - O Provedor de Contatos é um componente do provedor de conteúdo do Android. Ele mantém três tipos de + O Provedor de Contatos é um componente do provedor de conteúdo do Android. Ele mantém três tipos de dados sobre uma pessoa, sendo cada um deles correspondente a uma tabela fornecida pelo provedor, como ilustrado na figura 1:

    @@ -199,7 +199,7 @@ de dados de uma pessoa, ele permite diversos contatos brutos para a mesma pessoa {@link android.provider.ContactsContract.SyncColumns#ACCOUNT_TYPE}. - O formato desse nome é específico deste tipo de conta. + O formato desse nome é específico deste tipo de conta. Não se trata necessariamente de um endereço de e-mail. @@ -239,7 +239,7 @@ de dados de uma pessoa, ele permite diversos contatos brutos para a mesma pessoa
    • O nome de um contato bruto não é armazenado em sua linha em - {@link android.provider.ContactsContract.RawContacts}. Em vez disso, é armazenado na + {@link android.provider.ContactsContract.RawContacts}. Em vez disso, é armazenado na tabela {@link android.provider.ContactsContract.Data}, em uma linha {@link android.provider.ContactsContract.CommonDataKinds.StructuredName}. Os contatos brutos têm apenas uma linha desse tipo na tabela {@link android.provider.ContactsContract.Data}. @@ -275,7 +275,7 @@ de dados de uma pessoa, ele permite diversos contatos brutos para a mesma pessoa Configurações da conta.

      - Suponhamos que Emily Dickinson abra uma janela do navegador, acesse o Gmail como + Suponhamos que Emily Dickinson abra uma janela do navegador, acesse o Gmail como emily.dickinson@gmail.com, abra Contatos e adicione "Thomas Higginson". Mais tarde, ela acessa o Gmail como emilyd@gmail.com e envia um e-mail para "Thomas Higginson", o que automaticamente @@ -309,7 +309,7 @@ de dados de uma pessoa, ele permite diversos contatos brutos para a mesma pessoa tipo de dados, como endereços de e-mail ou números de telefone. Por exemplo: se "Thomas Higginson" para {@code emilyd@gmail.com} (a linha do contato bruto de Thomas Higginson associada à conta Google emilyd@gmail.com) tem um endereço de e-mail pessoal - thigg@gmail.com e um de trabalho + thigg@gmail.com e um de trabalho thomas.higginson@gmail.com, o Provedor de Contatos armazena as duas linhas de endereço de e-mail e vincula ambas ao contato bruto.

      @@ -490,7 +490,7 @@ de dados de uma pessoa, ele permite diversos contatos brutos para a mesma pessoa {@code android.provider.ContactsContract.ContactsColumns#LOOKUP_KEY} do contato continuará apontado para a linha do contato para permitir o uso de {@code android.provider.ContactsContract.ContactsColumns#LOOKUP_KEY} - e manter ligações com contatos "favoritos" e assim por diante. Essa coluna tem o próprio formato, que + e manter ligações com contatos "favoritos" e assim por diante. Essa coluna tem o próprio formato, que não tem nenhuma relação com o formato da coluna {@code android.provider.BaseColumns#_ID}.

      @@ -981,7 +981,7 @@ public Loader<Cursor> onCreateLoader(int id, Bundle args) { {@code android.provider.BaseColumns#_ID} do contato bruto como o valor {@link android.provider.ContactsContract.DataColumns#RAW_CONTACT_ID}. Contudo, esse valor não está disponível ao criar a {@link android.content.ContentProviderOperation} - para a linha de dados porque + para a linha de dados porque {@link android.content.ContentProviderOperation} ainda não foi aplicada à linha de contato bruto. Para trabalhar com isso, a classe {@link android.content.ContentProviderOperation.Builder} tem o método {@link android.content.ContentProviderOperation.Builder#withValueBackReference(String, int) withValueBackReference()}. @@ -1403,7 +1403,7 @@ StructuredPostal.CONTENT_URI}, RawContacts.CONTENT_TYPE}, tipo MIME para um grupo de contatos brutos. - Exibe a tela Adicionar contato do aplicativo de contatos do dispositivo. + Exibe a tela Adicionar contato do aplicativo de contatos do dispositivo. São exibidos os valores extras adicionados à intenção. Se enviada com {@link android.app.Activity#startActivityForResult(Intent, int) startActivityForResult()}, a URI de conteúdo do contato bruto recentemente adicionado é passada de volta @@ -1636,7 +1636,7 @@ startActivity(insertIntent); a disponibilidade dos dados dos contatos mesmo quando o dispositivo não está conectado à rede.

      - Embora seja possível implementar a sincronização de diversos modos, o sistema Android fornece + Embora seja possível implementar a sincronização de diversos modos, o sistema Android fornece uma estrutura de sincronização de extensão que automatiza as seguintes tarefas:

        @@ -1652,7 +1652,7 @@ startActivity(insertIntent);

      Para usar essa estrutura, deve-se fornecer uma extensão do adaptador de sincronização. Cada adaptador de sincronização é exclusivo - de um serviço e um provedor de conteúdo, mas pode tratar diversos nomes de conta do mesmo serviço. + de um serviço e um provedor de conteúdo, mas pode tratar diversos nomes de conta do mesmo serviço. A estrutura também permite diversos adaptadores de sincronização para o mesmo serviço e provedor.

      Classes e arquivos do adaptador de sincronização

      @@ -1830,7 +1830,7 @@ elemento <Textos de fluxos sociais

      - Itens de fluxo sempre são associados a um contato bruto. + Itens de fluxo sempre são associados a um contato bruto. O {@code android.provider.ContactsContract.StreamItemsColumns#RAW_CONTACT_ID} conecta-se ao valor _ID do contato bruto. O tipo e o nome da conta do contato bruto também são armazenados na linha do item de fluxo. @@ -1861,17 +1861,17 @@ elemento <

      {@code android:icon}
      - + Recurso desenhável do Android que o aplicativo de contatos exibe próximo aos dados. Use isso para indicar ao usuário que os dados são advindos do seu serviço.
      {@code android:summaryColumn}
      - O nome de coluna do primeiro de dois valores recuperados da linha de dados. + O nome de coluna do primeiro de dois valores recuperados da linha de dados. O valor é exibido como a primeira linha da entrada para essa linha de dados. A primeira linha destina-se ao uso como um resumo dos dados, mas isso é opcional. Veja também android:detailColumn. diff --git a/docs/html-intl/intl/pt-br/guide/topics/providers/content-provider-basics.jd b/docs/html-intl/intl/pt-br/guide/topics/providers/content-provider-basics.jd index 5005f9208bfe7..7bbca94bd937e 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/providers/content-provider-basics.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/providers/content-provider-basics.jd @@ -216,7 +216,7 @@ page.title=Preceitos do provedor de conteúdo Os aplicativos acessam dados a partir de um provedor de conteúdo com um objeto cliente {@link android.content.ContentResolver}. Esse objeto tem métodos que chamam métodos de nome idêntico no objeto do provedor, uma instância de uma das subclasses - concretas de {@link android.content.ContentProvider}. + concretas de {@link android.content.ContentProvider}. Os métodos {@link android.content.ContentResolver} fornecem as funções básicas do "CRUD" (criar, recuperar, atualizar e excluir) de armazenamento persistente.

      @@ -251,7 +251,7 @@ mCursor = getContentResolver().query(

    A tabela 2 mostra como os argumentos para - {@link android.content.ContentResolver#query + {@link android.content.ContentResolver#query query(Uri,projection,selection,selectionArgs,sortOrder)} correspondem a uma declaração SQL SELECT:

    @@ -310,7 +310,7 @@ mCursor = getContentResolver().query( {@link android.provider.UserDictionary.Words#CONTENT_URI} contém a URI de conteúdo da tabela de "palavras" do dicionário do usuário. O objeto {@link android.content.ContentResolver} analisa a autoridade da URI e usa-na para "determinar" o provedor - comparando a autoridade a uma tabela de provedores conhecidos do sistema. + comparando a autoridade a uma tabela de provedores conhecidos do sistema. O {@link android.content.ContentResolver} pode, então, enviar os argumentos da consulta ao provedor correto.

    @@ -344,7 +344,7 @@ Uri singleUri = ContentUris.withAppendedId(UserDictionary.Words.CONTENT_URI,4);

    Observação: as classes {@link android.net.Uri} e {@link android.net.Uri.Builder} - contêm métodos convenientes para a construção de objetos de URI bem formados a partir de strings. + contêm métodos convenientes para a construção de objetos de URI bem formados a partir de strings. As {@link android.content.ContentUris} contêm métodos conveniente para anexar valores de ID a uma URI. O fragmento anterior usa {@link android.content.ContentUris#withAppendedId withAppendedId()} para anexar um ID à URI de conteúdo UserDictionary. @@ -359,7 +359,7 @@ Uri singleUri = ContentUris.withAppendedId(UserDictionary.Words.CONTENT_URI,4);

    Por uma questão de clareza, os fragmentos de código nesta seção chamam - {@link android.content.ContentResolver#query ContentResolver.query()} no "encadeamento da IU". + {@link android.content.ContentResolver#query ContentResolver.query()} no "encadeamento da IU". No código atual, contudo, deve-se realizar consultas assincronamente em um encadeamento separado. Um modo de fazê-lo é usar a classe {@link android.content.CursorLoader}, descrita com mais detalhes no guia @@ -567,7 +567,7 @@ selectionArgs[0] = mUserInput;

    O método cliente {@link android.content.ContentResolver#query ContentResolver.query()} sempre retorna um {@link android.database.Cursor} contendo as colunas especificadas pela projeção - da consulta para as linhas que atendem aos critérios de seleção da consulta. + da consulta para as linhas que atendem aos critérios de seleção da consulta. Um objeto {@link android.database.Cursor} fornece acesso para leitura aleatório para as linhas e colunas que contém. Usando métodos {@link android.database.Cursor}, é possível repetir as linhas nos resultados, determinar o tipo dos dados de cada coluna, extrair os dados de uma coluna e examinar @@ -946,7 +946,7 @@ mRowsDeleted = getContentResolver().delete( Para acessar um provedor em "modo de lote", cria-se uma matriz de objetos {@link android.content.ContentProviderOperation} e, em seguida, envia-os a um provedor de conteúdo com - {@link android.content.ContentResolver#applyBatch ContentResolver.applyBatch()}. Confere-se a + {@link android.content.ContentResolver#applyBatch ContentResolver.applyBatch()}. Confere-se a autoridade do provedor de conteúdo para esse método em vez de para uma URI de conteúdo específica. Isso permite que cada objeto {@link android.content.ContentProviderOperation} na matriz trabalhe com uma tabela diferente. Chamar {@link android.content.ContentResolver#applyBatch @@ -954,7 +954,7 @@ mRowsDeleted = getContentResolver().delete(

    A descrição da classe de contrato {@link android.provider.ContactsContract.RawContacts} - contém um fragmento de código que demonstra a inserção em lote. + contém um fragmento de código que demonstra a inserção em lote. O aplicativo de exemplo do Gerente de contato contém um exemplo de acesso em lote em seu arquivo de origem ContactAdder.java. @@ -1089,7 +1089,7 @@ O aplicativo de exemplo do item/vnd.example.line2

    - A maioria dos provedores define constantes de classe de contrato para os tipos MIME que usam. + A maioria dos provedores define constantes de classe de contrato para os tipos MIME que usam. A classe de contrato {@link android.provider.ContactsContract.RawContacts} do Provedor de Contatos, por exemplo, define a constante {@link android.provider.ContactsContract.RawContacts#CONTENT_ITEM_TYPE} para o tipo MIME diff --git a/docs/html-intl/intl/pt-br/guide/topics/providers/content-provider-creating.jd b/docs/html-intl/intl/pt-br/guide/topics/providers/content-provider-creating.jd index 11ad4c3b1cca8..6ae7b2d6ee3d1 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/providers/content-provider-creating.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/providers/content-provider-creating.jd @@ -203,7 +203,7 @@ Projeto de armazenamento de dados.

    • O sistema Android contém uma API de banco de dados SQLite que os provedores do Android usam - para armazenar dados orientados a tabela. + para armazenar dados orientados a tabela. A classe {@link android.database.sqlite.SQLiteOpenHelper} ajuda a criar bancos de dados e a classe {@link android.database.sqlite.SQLiteDatabase} é a classe de base para acessar banco de dados. @@ -539,7 +539,7 @@ public class ExampleProvider extends ContentProvider {

      - Observe que esses métodos têm a mesma assinatura dos métodos + Observe que esses métodos têm a mesma assinatura dos métodos {@link android.content.ContentResolver} de mesmo nome.

      @@ -569,7 +569,7 @@ public class ExampleProvider extends ContentProvider {

    Implementação do método query()

    - + O método {@link android.content.ContentProvider#query(Uri, String[], String, String[], String) ContentProvider.query()} precisa retornar um objeto {@link android.database.Cursor} ou, se falhar, gerar uma {@link java.lang.Exception}. Se você estiver usando um banco de dados SQLite @@ -778,7 +778,7 @@ protected static final class MainDatabaseHelper extends SQLiteOpenHelper { Para tipos de dados comuns como texto, HTML ou JPEG, {@link android.content.ContentProvider#getType(Uri) getType()} deve retornar o tipo MIME padrão daqueles dados. Há uma lista completa desse tipos de padrão - no site de + no site de Tipos de mídia MIME IANA.

    @@ -981,7 +981,7 @@ vnd.android.cursor.item/vnd.com.example.provider.table1 Permissão de leitura, gravação ou leitura/gravação para uma URI de conteúdo no provedor. Especifica-se cada URI que se deseja controlar com um elemento filho - <path-permission> + <path-permission> do elemento <provider>. Para cada URI de conteúdo, pode-se especificar uma permissão de leitura/gravação, uma permissão de leitura, uma permissão de gravação ou as três. As permissões diff --git a/docs/html-intl/intl/pt-br/guide/topics/providers/content-providers.jd b/docs/html-intl/intl/pt-br/guide/topics/providers/content-providers.jd index c9574f6b90c6e..48f4cd49843d6 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/providers/content-providers.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/providers/content-providers.jd @@ -52,12 +52,12 @@ dados e fornecem mecanismos para definir a segurança dos dados. Provedores de c padrão que conecta dados em um processo com código em execução em outro processo.

    - Quando desejar acessar dados em um provedor de conteúdo, você usa o - objeto {@link android.content.ContentResolver} no + Quando desejar acessar dados em um provedor de conteúdo, você usa o + objeto {@link android.content.ContentResolver} no {@link android.content.Context} do aplicativo para se comunicar com o provedor como cliente. O objeto {@link android.content.ContentResolver} se comunica com o objeto provedor, uma instância de uma classe que implementa {@link android.content.ContentProvider}. O objeto - provedor recebe solicitações de dados de clientes, realiza a ação solicitada e + provedor recebe solicitações de dados de clientes, realiza a ação solicitada e devolve os resultados.

    @@ -68,10 +68,10 @@ dados e fornecem mecanismos para definir a segurança dos dados. Provedores de c

    O Android propriamente dito inclui provedores de conteúdo que gerenciam dados como áudio, vídeo, imagens e - informações de contato pessoais. Alguns deles estão listados na documentação de - referência do + informações de contato pessoais. Alguns deles estão listados na documentação de + referência do pacote android.provider - . Com algumas restrições, esses provedores podem ser acessados por qualquer aplicativo + . Com algumas restrições, esses provedores podem ser acessados por qualquer aplicativo Android.

    Os tópicos a seguir descrevem provedores de conteúdo em mais detalhes: diff --git a/docs/html-intl/intl/pt-br/guide/topics/providers/document-provider.jd b/docs/html-intl/intl/pt-br/guide/topics/providers/document-provider.jd index 25aab7aa7a9d2..b2e040ecefa55 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/providers/document-provider.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/providers/document-provider.jd @@ -139,7 +139,7 @@ dispositivos de armazenamento USB transitórios ou login/logout do usuário.N documentos.

  • Cada back-end de armazenamento apresenta -arquivos e diretórios individuais referenciando-os com um +arquivos e diretórios individuais referenciando-os com um {@link android.provider.DocumentsContract.Document#COLUMN_DOCUMENT_ID} exclusivo. IDs de documentos devem ser exclusivos e não podem mudar depois de emitidos, pois são usados para concessões persistentes da URI em reinicializações do dispositivo.
  • @@ -236,7 +236,7 @@ imagens armazenadas em um provedor de documentos. -

    Esta seção descreve como programar aplicativos clientes com base nas intenções +

    Esta seção descreve como programar aplicativos clientes com base nas intenções {@link android.content.Intent#ACTION_OPEN_DOCUMENT} e {@link android.content.Intent#ACTION_CREATE_DOCUMENT}.

    @@ -521,7 +521,7 @@ os arquivos, o que, obviamente, não é o ideal.

    Para evitar que isso aconteça, você pode manter as permissões que o sistema forneceu ao aplicativo. Efetivamente, o aplicativo "toma" a concessão de permissão da URI persistente -que o sistema está oferecendo. Isso concede ao usuário um acesso contínuo aos arquivos +que o sistema está oferecendo. Isso concede ao usuário um acesso contínuo aos arquivos por meio do aplicativo mesmo se o dispositivo for reiniciado:

    @@ -624,7 +624,7 @@ em dispositivos que executam o Android 4.4 ou posteriores. Se você deseja que o aplicativo seja compatível com {@link android.content.Intent#ACTION_GET_CONTENT} para adaptar-se a dispositivos que executam o Android 4.3 ou versões anteriores, é necessário desativar o filtro de intenção {@link android.content.Intent#ACTION_GET_CONTENT} -no manifesto para dispositivos que executam Android 4.4 ou versões posteriores. +no manifesto para dispositivos que executam Android 4.4 ou versões posteriores. Um provedor de documentos e {@link android.content.Intent#ACTION_GET_CONTENT} devem ser avaliados de forma mutuamente exclusiva. Se houver compatibilidade com ambos simultaneamente, o aplicativo aparecerá duas vezes na IU do seletor do sistema, oferecendo dois meios de acesso diff --git a/docs/html-intl/intl/pt-br/guide/topics/resources/accessing-resources.jd b/docs/html-intl/intl/pt-br/guide/topics/resources/accessing-resources.jd index f196dfeae779f..de8b5df5e4868 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/resources/accessing-resources.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/resources/accessing-resources.jd @@ -11,7 +11,7 @@ parent.link=index.html {@code R.drawable.myimage}
  • Recursos podem ser referenciados de recursos usando uma sintaxe XML especial, como {@code @drawable/myimage}
  • -
  • Também é possível acessar os recursos do aplicativo com métodos em +
  • Também é possível acessar os recursos do aplicativo com métodos em {@link android.content.res.Resources}
  • @@ -43,10 +43,10 @@ parent.link=index.html

    Depois de fornecer um recurso no aplicativo (discutido em Fornecimento de recursos), é possível aplicá-lo -referenciando seu ID de recurso. Todos os IDs de recursos são definidos na classe {@code R} do projeto, que +referenciando seu ID de recurso. Todos os IDs de recursos são definidos na classe {@code R} do projeto, que a ferramenta {@code aapt} gera automaticamente.

    -

    Quando o aplicativo é compilado, {@code aapt} gera a classe {@code R}, que contém +

    Quando o aplicativo é compilado, {@code aapt} gera a classe {@code R}, que contém IDs de recursos para todos os recursos no diretório {@code res/}. Para cada tipo de recurso, há uma subclasse {@code R} (por exemplo, {@code R.drawable} para todos os recursos desenháveis) e, para cada recurso daquele tipo, há um número inteiro @@ -60,7 +60,7 @@ verificá-la para descobrir um ID de recurso. Ele é sempre composto de:

    string}, {@code drawable} e {@code layout}. Para saber mais sobre os diferentes tipos, consulte Tipos de recursos.
  • O nome do recurso, que é: o nome do arquivo, -excluindo a extensão; ou o valor no atributo {@code android:name} do XML, se o +excluindo a extensão; ou o valor no atributo {@code android:name} do XML, se o recurso for um valor simples (como uma string).
  • @@ -101,7 +101,7 @@ com {@link android.content.Context#getResources()}.

    @@ -123,7 +123,7 @@ public void onCreate(Bundle savedInstanceState) {

    O método de retorno de chamada onCreate() na Atividade é chamado pela estrutura do Android quando -ela é inicializada (veja a discussão sobre ciclos de vida no documento +ela é inicializada (veja a discussão sobre ciclos de vida no documento Atividades ).

    @@ -201,7 +201,7 @@ de layout associados a cada uma delas.

    valores. Cada elemento filho deve definir LayoutParams apropriados para seu pai, embora possa também definir diferentes LayoutParams para os próprios filhos.

    -

    Todos os grupos de vistas contêm largura e altura (layout_width e +

    Todos os grupos de vistas contêm largura e altura (layout_width e layout_height) e cada vista é obrigatória para defini-las. Muitos LayoutParams também contêm margens e bordas opcionais.

    @@ -229,7 +229,7 @@ Recursos disponíveis.

    Posição do layout

    A geometria de uma vista de um retângulo. As vistas têm uma localização, - expressa como um par de coordenadas esquerda e topo + expressa como um par de coordenadas esquerda e topo e duas dimensões, expressas como largura e altura. A unidade de localização e de dimensões é o pixel.

    @@ -262,7 +262,7 @@ desnecessárias, chamados {@link android.view.View#getRight()} e {@link android.

    O primeiro par é conhecido como largura medida e altura medida. Essas dimensões definem o tamanho que a vista terá - dentro da vista pai. + dentro da vista pai. Para obter as dimensões medidas, chamam-se {@link android.view.View#getMeasuredWidth()} e {@link android.view.View#getMeasuredHeight()}.

    @@ -368,7 +368,7 @@ partially or totally obscuring them (unless the newer object is transparent).

    Criação de layouts com um adaptador

    Quando o conteúdo do layout é dinâmico ou não predeterminado, é possível usar um layout que -torne {@link android.widget.AdapterView} uma subclasse para preencher o layout com vistas em tempo de execução. +torne {@link android.widget.AdapterView} uma subclasse para preencher o layout com vistas em tempo de execução. Uma subclasse da classe {@link android.widget.AdapterView} usa um {@link android.widget.Adapter} para agrupar dados ao seu layout. O {@link android.widget.Adapter} se comporta como um intermediário entre a fonte dos dados e o layout do {@link android.widget.AdapterView} — o {@link android.widget.Adapter} @@ -399,7 +399,7 @@ a um {@link android.widget.Adapter}, o que recupera dados de uma fonte externa e android.view.View} que representa cada entrada de dados.

    O Android oferece diversas subclasses de {@link android.widget.Adapter} que são úteis para -recuperar diferentes tipos de dados e criar vistas de um {@link android.widget.AdapterView}. +recuperar diferentes tipos de dados e criar vistas de um {@link android.widget.AdapterView}. Os dois adaptadores mais comuns são:

    @@ -438,7 +438,7 @@ getView()} para retornar o tipo de vista que deseja para cada item.

    {@link android.widget.SimpleCursorAdapter}
    -
    Use este adaptador quando os dados vierem de um {@link android.database.Cursor}. +
    Use este adaptador quando os dados vierem de um {@link android.database.Cursor}. Ao usar {@link android.widget.SimpleCursorAdapter}, é necessário especificar um layout a usar para cada linha no {@link android.database.Cursor} e que colunas no {@link android.database.Cursor} devem ser inseridas em determinadas vistas do layout. Por exemplo: se você deseja criar uma lista @@ -466,7 +466,7 @@ fromColumns} na vista {@code toViews} correspondente.

    .
    -

    Se durante o curso de vida do aplicativo, você mudar os dados subjacentes lidos +

    Se durante o curso de vida do aplicativo, você mudar os dados subjacentes lidos pelo adaptador, chame {@link android.widget.ArrayAdapter#notifyDataSetChanged()}. Isso notificará à vista anexada que os dados foram alterados e que ela deve se atualizar.

    diff --git a/docs/html-intl/intl/pt-br/guide/topics/ui/dialogs.jd b/docs/html-intl/intl/pt-br/guide/topics/ui/dialogs.jd index 2cbedbebdebf3..71e617677507b 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/ui/dialogs.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/ui/dialogs.jd @@ -32,7 +32,7 @@ page.tags=diálogodealerta,fragmentodediálogo
  • {@link android.app.DialogFragment}
  • {@link android.app.AlertDialog}
  • - +

    Veja também

    1. Guia de projeto de caixas de diálogo
    2. @@ -235,8 +235,8 @@ AlertDialog dialog = builder.create();

      Os métodos set...Button() exigem um título para o botão (fornecido -por um recurso de string) e um -{@link android.content.DialogInterface.OnClickListener} que defina a ação a realizar +por um recurso de string) e um +{@link android.content.DialogInterface.OnClickListener} que defina a ação a realizar quando o usuário pressionar o botão.

      Há três botões de ação diferente que podem ser adicionados:

      @@ -248,7 +248,7 @@ quando o usuário pressionar o botão.

      Neutro
      É o que se deve usar quando houver a opção de o usuário não querer continuar a ação, mas não necessariamente cancelá-la. Ele aparece entre os botões positivo - e negativo. Por exemplo: a ação pode ser "Notifique-me mais tarde".
      + e negativo. Por exemplo: a ação pode ser "Notifique-me mais tarde".

      É possível adicionar somente um de cada tipo de botão a uma {@link @@ -271,7 +271,7 @@ Caixa de diálogo com um título e uma lista.

    3. Lista de escolhas múltiplas persistentes (caixas de seleção)
    4. -

      Para criar uma lista de escolha única como a da figura 3, +

      Para criar uma lista de escolha única como a da figura 3, use o método {@link android.app.AlertDialog.Builder#setItems setItems()}:

      @@ -291,7 +291,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
       
       

      Como a lista aparece na área do conteúdo da caixa de diálogo, a caixa não pode exibir uma mensagem e uma lista, e será preciso definir um título -para ela com {@link android.app.AlertDialog.Builder#setTitle setTitle()}. +para ela com {@link android.app.AlertDialog.Builder#setTitle setTitle()}. Para especificar os itens da lista, chame {@link android.app.AlertDialog.Builder#setItems setItems()} passando uma matriz. Alternativamente, é possível especificar uma lista com {@link @@ -320,8 +320,8 @@ Lista de itens de múltipla escolha.

      Para adicionar uma lista de itens de múltipla escolha (caixas de seleção) ou itens de escolha única (botões de rádio), use os métodos {@link android.app.AlertDialog.Builder#setMultiChoiceItems(Cursor,String,String, -DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} ou -{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} ou +{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()} respectivamente.

      Por exemplo, a seguir apresenta-se como criar uma lista de múltipla escolha como @@ -346,7 +346,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { // If the user checked the item, add it to the selected items mSelectedItems.add(which); } else if (mSelectedItems.contains(which)) { - // Else, if the item is already in the array, remove it + // Else, if the item is already in the array, remove it mSelectedItems.remove(Integer.valueOf(which)); } } @@ -373,7 +373,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {

      Embora a lista tradicional e uma lista com botões de opção forneçam uma ação de "escolha única", deve-se usar {@link -android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()} se você desejar manter a escolha do usuário. Ou seja, se a caixa de diálogo abrir novamente mais tarde, deve indicar qual é a escolha atual do usuário, portanto deve-se criar uma lista com botões de opção.

      @@ -442,7 +442,7 @@ deve-se alterar a família da fonte para {@code "sans-serif"} para que os campos um estilo de fonte compatível.

      Para inflar o layout no {@link android.support.v4.app.DialogFragment}, -obtenha um {@link android.view.LayoutInflater} com +obtenha um {@link android.view.LayoutInflater} com {@link android.app.Activity#getLayoutInflater()} e chame {@link android.view.LayoutInflater#inflate inflate()}, em que o primeiro parâmetro é o ID de recurso do layout e o segundo é uma vista pai do layout. @@ -470,7 +470,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { public void onClick(DialogInterface dialog, int id) { LoginDialogFragment.this.getDialog().cancel(); } - }); + }); return builder.create(); }

      @@ -505,7 +505,7 @@ uma interface por meio da qual entrega os eventos de volta à atividade do host:
       public class NoticeDialogFragment extends DialogFragment {
      -    
      +
           /* The activity that creates an instance of this dialog fragment must
            * implement this interface in order to receive event callbacks.
            * Each method passes the DialogFragment in case the host needs to query it. */
      @@ -513,10 +513,10 @@ public class NoticeDialogFragment extends DialogFragment {
               public void onDialogPositiveClick(DialogFragment dialog);
               public void onDialogNegativeClick(DialogFragment dialog);
           }
      -    
      +
           // Use this instance of the interface to deliver action events
           NoticeDialogListener mListener;
      -    
      +
           // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
           @Override
           public void onAttach(Activity activity) {
      @@ -543,7 +543,7 @@ dela por meio de uma implementação da interface {@code NoticeDialogListener}:<
       public class MainActivity extends FragmentActivity
                                 implements NoticeDialogFragment.NoticeDialogListener{
           ...
      -    
      +
           public void showNoticeDialog() {
               // Create an instance of the dialog fragment and show it
               DialogFragment dialog = new NoticeDialogFragment();
      @@ -656,7 +656,7 @@ public class CustomDialogFragment extends DialogFragment {
               // Inflate the layout to use as dialog or embedded fragment
               return inflater.inflate(R.layout.purchase_items, container, false);
           }
      -  
      +
           /** The system calls this only when creating the layout in a dialog. */
           @Override
           public Dialog onCreateDialog(Bundle savedInstanceState) {
      @@ -678,7 +678,7 @@ ou como uma IU de tela cheia com base no tamanho da tela:

      public void showDialog() { FragmentManager fragmentManager = getSupportFragmentManager(); CustomDialogFragment newFragment = new CustomDialogFragment(); - + if (mIsLargeLayout) { // The device is using a large layout, so show the fragment as a dialog newFragment.show(fragmentManager, "dialog"); @@ -695,7 +695,7 @@ public void showDialog() { }
      -

      Para obter mais informações sobre a realização de operações de fragmentos, consulte o guia +

      Para obter mais informações sobre a realização de operações de fragmentos, consulte o guia Fragmentos.

      Nesse exemplo, o booleano mIsLargeLayout especifica se o dispositivo atual @@ -721,7 +721,7 @@ versões de recurso bool para diferentes tamanhos de tela:

      </resources> -

      Assim, é possível inicializar o valor {@code mIsLargeLayout} durante o método +

      Assim, é possível inicializar o valor {@code mIsLargeLayout} durante o método {@link android.app.Activity#onCreate onCreate()} da atividade:

      @@ -776,7 +776,7 @@ android.support.v4.app.DialogFragment#onDismiss onDismiss()} no {@link
       android.support.v4.app.DialogFragment}.

      Também é possível cancelar uma caixa de diálogo. Trata-se de um evento especial que indica que o usuário -se retirou explicitamente da caixa de diálogo sem concluir a tarefa. Isso ocorre se o usuário pressionar o botão +se retirou explicitamente da caixa de diálogo sem concluir a tarefa. Isso ocorre se o usuário pressionar o botão Voltar, tocar na tela fora da área da caixa de diálogo ou se você chamar {@link android.app.Dialog#cancel()} explicitamente no {@link android.app.Dialog} (como em resposta a um botão "Cancelar" na caixa de diálogo).

      diff --git a/docs/html-intl/intl/pt-br/guide/topics/ui/menus.jd b/docs/html-intl/intl/pt-br/guide/topics/ui/menus.jd index 833f8966b4391..6bdb370740d30 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/ui/menus.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/ui/menus.jd @@ -83,9 +83,9 @@ não têm), então você deve migrar usando a barra de ação para fornecer aces e outras opções.

      Consulte a seção Criação de um menu de opções.

      - +
      Modo de ação contextual e menu de contexto
      - +
      Um menu de contexto é um menu flutuante que aparece quando o usuário realiza um clique longo em um elemento. Ele fornece ações que afetam o conteúdo selecionado ou a estrutura do contexto. @@ -94,7 +94,7 @@ que afetam o conteúdo selecionado em uma barra no topo da tela e permite que o selecione vários itens.

      Consulte a seção Criação de menus contextuais.

      - +
      Menu pop-up
      Um menu pop-up exibe itens em uma lista vertical ancorada à vista que apresentou o menu. É bom para fornecer um estouro de ações relacionado a conteúdo específico @@ -135,7 +135,7 @@ do projeto e crie o menu com os seguintes elementos:

      <item>
      Cria um {@link android.view.MenuItem}, que representa um único item em um menu. Este elemento pode conter um elemento <menu> aninhado para criar um submenu.
      - +
      <group>
      Um recipiente invisível e opcional para os elementos {@code <item>}. Ele permite que você categorize itens de menu para que eles compartilhem propriedades como estado ativo e visibilidade. Para obter mais informações, @@ -218,7 +218,7 @@ para o contexto de atividade atual, como "Buscar", "Escrever e-mail" e "Configur foi desenvolvido:

        -
      • Caso tenha desenvolvido o aplicativo para Android 2.3.x (API de nível 10) ou +
      • Caso tenha desenvolvido o aplicativo para Android 2.3.x (API de nível 10) ou inferior, os conteúdos do menu de opções aparecerão na parte inferior da tela, quando o usuário pressionar o botão Menu, como exibido na figura 1. Quando aberto, a primeira parte visível é o menu @@ -363,7 +363,7 @@ são apresentados na barra de ação. Quando um evento ocorre e você quer reali você deve chamar {@link android.app.Activity#invalidateOptionsMenu invalidateOptionsMenu()} para pedir que o sistema chame {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}.

        -

        Observação: +

        Observação: você nunca deve alterar os itens no menu de opções com base no {@link android.view.View} atualmente em foco. Quando estiver no modo de toque (quando o usuário não está usando cursor de bola ou um teclado), as vistas não podem ter foco, então você nunca deve usar o foco como base para modificar @@ -742,8 +742,8 @@ que exibe um menu pop-up:

         <ImageButton
        -    android:layout_width="wrap_content" 
        -    android:layout_height="wrap_content" 
        +    android:layout_width="wrap_content"
        +    android:layout_height="wrap_content"
             android:src="@drawable/ic_overflow_holo_dark"
             android:contentDescription="@string/descr_overflow_button"
             android:onClick="showPopup" />
        @@ -901,7 +901,7 @@ android.view.MenuItem#setChecked(boolean) setChecked()}.

        (como {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}). É aqui que você deve definir o estado da caixa de seleção, pois a caixa de seleção ou o botão de rádio não altera o seu estado automaticamente. É possível consultar o estado do item (como ele era antes -do usuário selecioná-lo) com {@link android.view.MenuItem#isChecked()} e, em seguida, definir o estado marcado com +do usuário selecioná-lo) com {@link android.view.MenuItem#isChecked()} e, em seguida, definir o estado marcado com {@link android.view.MenuItem#setChecked(boolean) setChecked()}. Por exemplo:

        @@ -1023,9 +1023,9 @@ do filtro de intenção. Por exemplo:

        </intent-filter>
        -

        Leia mais sobre a criação de filtros de intenção no documento +

        Leia mais sobre a criação de filtros de intenção no documento Intenções e filtros de intenções.

        -

        Para obter um exemplo de aplicativo que usa esta técnica, consulte o código de exemplo do +

        Para obter um exemplo de aplicativo que usa esta técnica, consulte o código de exemplo do Bloco de notas.

        diff --git a/docs/html-intl/intl/pt-br/guide/topics/ui/notifiers/notifications.jd b/docs/html-intl/intl/pt-br/guide/topics/ui/notifiers/notifications.jd index 42563ace22482..d3fb4cfab2962 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/ui/notifiers/notifications.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/ui/notifiers/notifications.jd @@ -92,7 +92,7 @@ A classe {@link android.app.Notification.Builder Notification.Builder} foi adici

        As notificações, como parte importante da interface do usuário do Android, possuem as próprias diretrizes de projeto. As alterações do Material Design introduzidas no Android 5.0 (API de nível 21) são de importância específica e, por isso, recomenda-se revisar o treinamento do Material Design - para obter mais informações. Para saber como projetar notificações e suas interações, leia o guia de projeto + para obter mais informações. Para saber como projetar notificações e suas interações, leia o guia de projeto Notificações.

        Criação de uma notificação

        @@ -451,14 +451,14 @@ todas as notificações emitidas anteriormente. Adicione compatibilidade com Android 4.0.3 e mais antigos. Para fazer isto, especifique o pai da {@link android.app.Activity} que está iniciando adicionando um elemento <meta-data> - como o filho de + como o filho de <activity>.

        - Para este elemento, defina + Para este elemento, defina android:name="android.support.PARENT_ACTIVITY". Defina android:value="<parent_activity_name>", - onde <parent_activity_name> é o valor de + onde <parent_activity_name> é o valor de android:name para o elemento <activity> diff --git a/docs/html-intl/intl/pt-br/guide/topics/ui/overview.jd b/docs/html-intl/intl/pt-br/guide/topics/ui/overview.jd index d12bfe5fac8b5..d82ecf7aa8fa7 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/ui/overview.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/ui/overview.jd @@ -4,12 +4,12 @@ page.title=Visão geral da IU

        Todos os elementos da interface do usuário em um aplicativo para Android são criados usando objetos {@link android.view.View} e {@link android.view.ViewGroup}. Uma {@link android.view.View} é um objeto que desenha -algo na tela com o qual o usuário pode interagir. Um {@link android.view.ViewGroup} é um +algo na tela com o qual o usuário pode interagir. Um {@link android.view.ViewGroup} é um objeto que contém outros objetos {@link android.view.View} (e {@link android.view.ViewGroup}) para definir o layout da interface.

        O Android fornece uma coleção de subclasses {@link android.view.View} e {@link -android.view.ViewGroup} que oferecem controles de entrada comuns (como botões e campos de +android.view.ViewGroup} que oferecem controles de entrada comuns (como botões e campos de texto) e vários modelos de layout (como um layout linear ou relativo).

        @@ -30,7 +30,7 @@ de uma IU.

        criar uma árvore. Mas a forma mais fácil e efetiva de definir o layout é com um arquivo XML. O XML oferece uma estrutura legível por humanos para o layout, similar a HTML.

        -

        O nome de um elemento XML para uma vista é respectivo à classe do Android que ele representa. Portanto, um elemento +

        O nome de um elemento XML para uma vista é respectivo à classe do Android que ele representa. Portanto, um elemento <TextView> cria um widget {@link android.widget.TextView} na IU e um elemento <LinearLayout> cria um grupo de vistas de {@link android.widget.LinearLayout} .

        @@ -39,7 +39,7 @@ e um elemento <LinearLayout> cria um grupo de vistas de {@lin
         <?xml version="1.0" encoding="utf-8"?>
         <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -              android:layout_width="fill_parent" 
        +              android:layout_width="fill_parent"
                       android:layout_height="fill_parent"
                       android:orientation="vertical" >
             <TextView android:id="@+id/text"
        @@ -60,7 +60,7 @@ layout.

        Para obter um guia completo para criar um layout de IU, consulte Layouts XML. - +

        Componentes da interface do usuário

        Você não precisa criar toda a IU usando objetos {@link android.view.View} e {@link diff --git a/docs/html-intl/intl/pt-br/guide/topics/ui/settings.jd b/docs/html-intl/intl/pt-br/guide/topics/ui/settings.jd index f95966c37578d..c00b461499d4f 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/ui/settings.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/ui/settings.jd @@ -82,7 +82,7 @@ como programar as configurações do aplicativo por meio de APIs {@link android.

        Figura 1. Capturas de tela das configurações do aplicativo Mensagens -do Android. A seleção de um item definido por uma {@link android.preference.Preference} +do Android. A seleção de um item definido por uma {@link android.preference.Preference} abre uma interface para alterar a configuração.

        @@ -120,8 +120,8 @@ um dos seguintes tipos de dados:

      Como a IU de configurações do aplicativo é criada com objetos {@link android.preference.Preference} - em vez de objetos -{@link android.view.View}, é preciso usar uma subclasse {@link android.app.Activity} ou + em vez de objetos +{@link android.view.View}, é preciso usar uma subclasse {@link android.app.Activity} ou {@link android.app.Fragment} especializada para exibir as configurações de lista:

        @@ -226,8 +226,8 @@ android.preference.ListPreference}. Os dois itens contêm estes três atributos:
        {@code android:key}
        Esse atributo é necessário para preferências que persistem a um valor de dados. Ele especifica a chave exclusiva (uma string) que o sistema usa ao salvar o valor dessa configuração em {@link -android.content.SharedPreferences}. -

        As únicas instâncias em que esse atributo é dispensável ocorrem quando a preferência é um +android.content.SharedPreferences}. +

        As únicas instâncias em que esse atributo é dispensável ocorrem quando a preferência é um {@link android.preference.PreferenceCategory} ou {@link android.preference.PreferenceScreen}, ou quando a preferência especifica um {@link android.content.Intent} para invocar (com um elemento {@code <intent>}) ou um {@link android.app.Fragment} para exibir (com um atributo {@code android:fragment}).

        @@ -285,7 +285,7 @@ android.preference.PreferenceCategory}.

         <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        -    <PreferenceCategory 
        +    <PreferenceCategory
                 android:title="@string/pref_sms_storage_title"
                 android:key="pref_key_storage_settings">
                 <CheckBoxPreference
        @@ -293,12 +293,12 @@ android.preference.PreferenceCategory}.

        android:summary="@string/pref_summary_auto_delete" android:title="@string/pref_title_auto_delete" android:defaultValue="false"... /> - <Preference + <Preference android:key="pref_key_sms_delete_limit" android:dependency="pref_key_auto_delete" android:summary="@string/pref_summary_delete_limit" android:title="@string/pref_title_sms_delete"... /> - <Preference + <Preference android:key="pref_key_mms_delete_limit" android:dependency="pref_key_auto_delete" android:summary="@string/pref_summary_delete_limit" @@ -311,7 +311,7 @@ android.preference.PreferenceCategory}.

        Uso de subtelas

        -

        Para usar grupos de configurações em uma subtela (como ilustrado na figura 3), coloque o grupo +

        Para usar grupos de configurações em uma subtela (como ilustrado na figura 3), coloque o grupo de objetos {@link android.preference.Preference} dentro de {@link android.preference.PreferenceScreen}.

        @@ -588,11 +588,11 @@ dentro de um elemento raiz {@code <preference-headers>}. Por exemplo:

         <?xml version="1.0" encoding="utf-8"?>
         <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
        -    <header 
        +    <header
                 android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentOne"
                 android:title="@string/prefs_category_one"
                 android:summary="@string/prefs_summ_category_one" />
        -    <header 
        +    <header
                 android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentTwo"
                 android:title="@string/prefs_category_two"
                 android:summary="@string/prefs_summ_category_two" >
        @@ -636,7 +636,7 @@ public static class SettingsFragment extends PreferenceFragment {
         

        Exibição de cabeçalhos

        Para exibir os cabeçalhos de preferência, é preciso implementar o método de retorno de chamada {@link -android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} e chamar +android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} e chamar {@link android.preference.PreferenceActivity#loadHeadersFromResource loadHeadersFromResource()}. Por exemplo:

        @@ -672,15 +672,15 @@ ao {@link android.preference.PreferenceActivity} que especifica que arquivo XML carregar.

        Por exemplo, abaixo há um arquivo XML de cabeçalhos de preferência usado no Android 3.0 -e posterior ({@code res/xml/preference_headers.xml}):

        +e posterior ({@code res/xml/preference_headers.xml}):

         <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
        -    <header 
        +    <header
                 android:fragment="com.example.prefs.SettingsFragmentOne"
                 android:title="@string/prefs_category_one"
                 android:summary="@string/prefs_summ_category_one" />
        -    <header 
        +    <header
                 android:fragment="com.example.prefs.SettingsFragmentTwo"
                 android:title="@string/prefs_category_two"
                 android:summary="@string/prefs_summ_category_two" />
        @@ -692,18 +692,18 @@ mais antigas que a 3.0 ({@code res/xml/preference_headers_legacy.xml}):

         <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        -    <Preference 
        +    <Preference
                 android:title="@string/prefs_category_one"
                 android:summary="@string/prefs_summ_category_one"  >
        -        <intent 
        +        <intent
                     android:targetPackage="com.example.prefs"
                     android:targetClass="com.example.prefs.SettingsActivity"
                     android:action="com.example.prefs.PREFS_ONE" />
             </Preference>
        -    <Preference 
        +    <Preference
                 android:title="@string/prefs_category_two"
                 android:summary="@string/prefs_summ_category_two" >
        -        <intent 
        +        <intent
                     android:targetPackage="com.example.prefs"
                     android:targetClass="com.example.prefs.SettingsActivity"
                     android:action="com.example.prefs.PREFS_TWO" />
        @@ -975,11 +975,11 @@ da caixa de diálogo positiva e negativa:

        public class NumberPickerPreference extends DialogPreference { public NumberPickerPreference(Context context, AttributeSet attrs) { super(context, attrs); - + setDialogLayoutResource(R.layout.numberpicker_dialog); setPositiveButtonText(android.R.string.ok); setNegativeButtonText(android.R.string.cancel); - + setDialogIcon(null); } ... @@ -1194,7 +1194,7 @@ protected void onRestoreInstanceState(Parcelable state) { // Cast state to custom BaseSavedState and pass to superclass SavedState myState = (SavedState) state; super.onRestoreInstanceState(myState.getSuperState()); - + // Set this Preference's widget to reflect the restored state mNumberPicker.setValue(myState.value); } diff --git a/docs/html-intl/intl/pt-br/guide/topics/ui/ui-events.jd b/docs/html-intl/intl/pt-br/guide/topics/ui/ui-events.jd index e0ace1d4b3cac..2f88248b3eb20 100644 --- a/docs/html-intl/intl/pt-br/guide/topics/ui/ui-events.jd +++ b/docs/html-intl/intl/pt-br/guide/topics/ui/ui-events.jd @@ -30,7 +30,7 @@ uma coleção de interfaces aninhadas com retornos de chamada que podem ser defi chamadas de escutas de evento, são a sua passagem para capturar a interação do usuário com a IU.

        Geralmente, as escutas de evento são usadas para escutar a interação do usuário. -No entanto, há casos em que você pode querer estender uma classe View para criar um componente personalizado. +No entanto, há casos em que você pode querer estender uma classe View para criar um componente personalizado. Talvez você queira estender a classe {@link android.widget.Button} para deixar algo mais extravagante. Neste caso, você poderá definir os comportamentos de evento padrão para a classe usando manipuladores de evento.

        @@ -46,27 +46,27 @@ estiver registrada for ativada pela interação do usuário com o item na IU.

        onClick()
        -
        De {@link android.view.View.OnClickListener}. +
        De {@link android.view.View.OnClickListener}. Isto é chamado quando o usuário toca no item (no modo de toque), ou atribui foco ao item com as teclas de navegação ou cursor de bola e pressiona a tecla "enter" adequada ou pressiona o cursor de bola.
        onLongClick()
        -
        De {@link android.view.View.OnLongClickListener}. +
        De {@link android.view.View.OnLongClickListener}. Isto é chamado quando o usuário toca e mantém o item pressionado (no modo de toque), ou atribui foco ao item com as teclas de navegação ou cursor de bola e mantém pressionada a tecla "enter" adequada ou o cursor de bola (por um segundo).
        onFocusChange()
        -
        De {@link android.view.View.OnFocusChangeListener}. +
        De {@link android.view.View.OnFocusChangeListener}. Isto é chamado quando o usuário navega no ou do item, usando as teclas de navegação ou cursor de bola.
        onKey()
        -
        De {@link android.view.View.OnKeyListener}. +
        De {@link android.view.View.OnKeyListener}. Isto é chamado quando o usuário está com foco no item ou solta uma tecla de hardware no dispositivo.
        onTouch()
        -
        De {@link android.view.View.OnTouchListener}. +
        De {@link android.view.View.OnTouchListener}. Isto é chamado quando o usuário realiza uma ação qualificada como um toque de evento, incluindo o pressionamento, a liberação, ou qualquer outro gesto de movimento na tela (dentro dos limites do item).
        onCreateContextMenu()
        -
        De {@link android.view.View.OnCreateContextMenuListener}. +
        De {@link android.view.View.OnCreateContextMenuListener}. Isto é chamado quando um menu de contexto está sendo construído (como resultado de um "clique longo"). Consulte a discussão sobre menus de contexto no guia do desenvolvedor Menus .
        @@ -75,8 +75,8 @@ estiver registrada for ativada pela interação do usuário com o item na IU.

        Esses métodos são os únicos habitantes de suas respectivas interfaces. Para definir um desses métodos e lidar com seus eventos, implemente a interface aninhada na atividade ou defina-a como uma classe anônima. Em seguida, passe uma instância da implementação -para o respectivo método View.set...Listener(). (Ex.:, chame -{@link android.view.View#setOnClickListener(View.OnClickListener) setOnClickListener()} +para o respectivo método View.set...Listener(). (Ex.:, chame +{@link android.view.View#setOnClickListener(View.OnClickListener) setOnClickListener()} e passe-o à implementação de {@link android.view.View.OnClickListener OnClickListener}.)

        O exemplo abaixo mostra como registrar uma escuta de clique para um botão.

        @@ -121,17 +121,17 @@ public class ExampleActivity extends Activity implements OnClickListener { não tem valor de retorno, mas outros métodos de escuta de evento podem retornar um booleano. O motivo depende do evento. Para os poucos que retornam, apresenta-se a razão:

          -
        • {@link android.view.View.OnLongClickListener#onLongClick(View) onLongClick()} - - Isto retorna um booleano para indicar se você consumiu o evento e se ele deve ser levado adiante. - Ou seja, ele retorna verdadeiro para indicar que você lidou com o evento e não deve seguir adiante; +
        • {@link android.view.View.OnLongClickListener#onLongClick(View) onLongClick()} - + Isto retorna um booleano para indicar se você consumiu o evento e se ele deve ser levado adiante. + Ou seja, ele retorna verdadeiro para indicar que você lidou com o evento e não deve seguir adiante; ou retorna falso caso você não tenha lidado com ele e/ou o evento deva continuar para qualquer outra escuta de clique.
        • -
        • {@link android.view.View.OnKeyListener#onKey(View,int,KeyEvent) onKey()} - +
        • {@link android.view.View.OnKeyListener#onKey(View,int,KeyEvent) onKey()} - Isto retorna um booleano para indicar se você consumiu o evento e se ele deve ser levado adiante. - Ou seja, ele retorna verdadeiro para indicar que você lidou com o evento e não deve seguir adiante; + Ou seja, ele retorna verdadeiro para indicar que você lidou com o evento e não deve seguir adiante; ou retorna falso caso você não tenha lidado com ele e/ou o evento deva continuar para qualquer outra escuta de tecla.
        • -
        • {@link android.view.View.OnTouchListener#onTouch(View,MotionEvent) onTouch()} - +
        • {@link android.view.View.OnTouchListener#onTouch(View,MotionEvent) onTouch()} - Isto retorna um booleano para indicar se a escuta consome este evento. O importante é que este evento pode possuir várias ações que se seguem mutuamente. Portanto, se retornar falso quando o evento de ação inferior for recebido, você indicará que não consumiu o evento e que não está @@ -181,14 +181,14 @@ mas podem ter impacto direto na maneira de lidar com os eventos. Portanto, ao ge dentro de um layout, considere esses outros métodos:

          • {@link android.app.Activity#dispatchTouchEvent(MotionEvent) - Activity.dispatchTouchEvent(MotionEvent)} - Isto permite que {@link + Activity.dispatchTouchEvent(MotionEvent)} - Isto permite que {@link android.app.Activity} intercepte todos os evento de toque antes de serem enviados à janela.
          • {@link android.view.ViewGroup#onInterceptTouchEvent(MotionEvent) ViewGroup.onInterceptTouchEvent(MotionEvent)} - Isto permite que {@link android.view.ViewGroup} assista aos eventos à medida que são enviados para as vistas filho.
          • {@link android.view.ViewParent#requestDisallowInterceptTouchEvent(boolean) ViewParent.requestDisallowInterceptTouchEvent(boolean)} - Chame isto - sobre uma Vista pai para indicar que ela não deve interceptar eventos de toque com {@link + sobre uma Vista pai para indicar que ela não deve interceptar eventos de toque com {@link android.view.ViewGroup#onInterceptTouchEvent(MotionEvent)}.
          @@ -199,7 +199,7 @@ Quando um usuário está navegando em uma interface do usuário com teclas direc ver o que aceitará entrada. Se o dispositivo tiver capacidades de toque, no entanto, e o usuário começar a interagir com a interface por meio de toque, então não é mais necessário destacar itens ou fornecer foco para uma vista específica. Contudo, há um modo -de interação chamado "modo de toque". +de interação chamado "modo de toque".

          Para dispositivos com capacidades de toque, quando o usuário toca na tela, o dispositivo @@ -214,7 +214,7 @@ sairá do modo de toque e encontrará uma vista para atribuir foco. Agora, o usu com a interface do usuário sem tocar na tela.

          -O estado de modo de toque é mantido em todo o sistema (todas as janelas e atividades). +O estado de modo de toque é mantido em todo o sistema (todas as janelas e atividades). Para consultar o estado atual, é possível chamar {@link android.view.View#isInTouchMode} para ver se o dispositivo está no modo de toque no momento.

          @@ -282,7 +282,7 @@ como discutido na seção Escutas de evento acima. the framework will take care of measuring, laying out, and drawing the tree as appropriate.
    - +

    Note: The entire View tree is single threaded. You must always be on the UI thread when calling any method on any View. If you are doing work on other threads and want to update the state of a View diff --git a/docs/html-intl/intl/pt-br/preview/api-overview.jd b/docs/html-intl/intl/pt-br/preview/api-overview.jd index c16d84701d114..d638e71fc53c6 100644 --- a/docs/html-intl/intl/pt-br/preview/api-overview.jd +++ b/docs/html-intl/intl/pt-br/preview/api-overview.jd @@ -48,7 +48,7 @@ page.image=images/cards/card-n-apis_2x.png -

    O Android N ainda está em desenvolvimento ativo, mas agora você já pode testá-lo +

    O Android N ainda está em desenvolvimento ativo, mas agora você já pode testá-lo como parte do N Developer Preview. As seções a seguir destacam alguns dos novos recursos para desenvolvedores.

    @@ -62,7 +62,7 @@ novos recursos para desenvolvedores.

    Suporte a várias janelas

    -

    No Android N, introduzimos um recurso de multitarefa novo e muito solicitado +

    No Android N, introduzimos um recurso de multitarefa novo e muito solicitado na plataforma — o suporte a várias janelas.

    Agora os usuários podem abrir dois aplicativos na tela ao mesmo tempo.

    @@ -85,9 +85,9 @@ interage com outros aplicativos. -

    O suporte a várias janelas oferece novas formas de envolver os usuários, -particularmente em tablets e outros dispositivos com telas maiores. Você pode até ativar o recurso de arrastar e soltar -no aplicativo para permitir que os usuários arrastem conteúdo de ou para o aplicativo — uma ótima +

    O suporte a várias janelas oferece novas formas de envolver os usuários, +particularmente em tablets e outros dispositivos com telas maiores. Você pode até ativar o recurso de arrastar e soltar +no aplicativo para permitir que os usuários arrastem conteúdo de ou para o aplicativo — uma ótima maneira de aprimorar a experiência do usuário.

    É muito fácil adicionar suporte a várias janelas a seu aplicativo e configurar como ele @@ -103,7 +103,7 @@ deste tamanho. Você também pode desativar a exibição de várias janelas para

    Aprimoramentos de notificações

    -

    Reformulamos as notificações no Android N para facilitar e agilizar o +

    Reformulamos as notificações no Android N para facilitar e agilizar o uso. Entre as alterações estão:

    -

    Para obter mais informações sobre o recurso de armazenamento de chaves protegido por hardware, +

    Para obter mais informações sobre o recurso de armazenamento de chaves protegido por hardware, consulte o guia Armazenamento de chaves protegido por hardware.

    Além da confirmação de chaves, o Android N também introduziu @@ -717,9 +717,9 @@ consulte o guia Configuração de segurança de rede -

    No Android N, os aplicativos podem personalizar o comportamento de conexões seguras (HTTPS, TLS) -de forma segura, sem modificação no código, usando a -Configuração de segurança de rede declarativa em vez das +

    No Android N, os aplicativos podem personalizar o comportamento de conexões seguras (HTTPS, TLS) +de forma segura, sem modificação no código, usando a +Configuração de segurança de rede declarativa em vez das APIs programáticas propensas a erro (por exemplo, X509TrustManager).

    Recursos compatíveis:

    @@ -728,25 +728,25 @@ APIs programáticas propensas a erro (por exemplo, X509TrustManager).

    autoridades de certificado (CA) são confiáveis para as conexões seguras. Por exemplo, confiar em certificados autoassinados privados ou um restrito conjunto de CAs públicas. -
  • Substituições apenas em depuração. Permite que um desenvolvedor de aplicativos depure -conexões seguras do aplicativo com segurança, sem adicionar riscos à base +
  • Substituições apenas em depuração. Permite que um desenvolvedor de aplicativos depure +conexões seguras do aplicativo com segurança, sem adicionar riscos à base instalada.
  • -
  • Cancelamento do uso de tráfego de texto simples. Permite que um aplicativo seja protegido contra +
  • Cancelamento do uso de tráfego de texto simples. Permite que um aplicativo seja protegido contra o uso acidental de tráfego de texto simples.
  • Fixação de certificados. Um recurso avançado que permite que os aplicativos limitem quais chaves de servidor são confiáveis para conexões seguras.
  • -

    Para obter mais configurações, consulte Configuração de segurança +

    Para obter mais configurações, consulte Configuração de segurança de rede.

    Autoridade de certificado confiável padrão

    -

    Por padrão, os aplicativos direcionados ao Android N confiam apenas em certificados fornecidos pelo sistema -e não confiam mais em Autoridades de certificado (CA) adicionadas pelo usuário. Os aplicativos direcionados ao Android -N que querem confiar em CAs adicionadas pelo usuário devem usar a -Configuração de segurança de rede para +

    Por padrão, os aplicativos direcionados ao Android N confiam apenas em certificados fornecidos pelo sistema +e não confiam mais em Autoridades de certificado (CA) adicionadas pelo usuário. Os aplicativos direcionados ao Android +N que querem confiar em CAs adicionadas pelo usuário devem usar a +Configuração de segurança de rede para especificar como confiar nas CAs de usuário.

    Esquema de assinatura de APK v2

    @@ -804,18 +804,18 @@ o arquivo de programação para assinar aplicativos usando o plug-in do Andr

    No Android N, os aplicativos podem usar novas APIs para solicitar acesso a determinados diretórios de armazenamento externo, incluindo diretórios em mídias removíveis, tais como cartões SD. As novas APIs simplificam consideravelmente como o aplicativo acessa os -diretórios de armazenamento externo padrão, tais como o diretórioPictures. Os aplicativos, -como aplicativos de fotografia, podem usar essas APIs em vez de -READ_EXTERNAL_STORAGE, que concede acesso a todos os diretórios de -armazenamento, ou da Estrutura de acesso ao armazenamento, que faz o usuário navegar até +diretórios de armazenamento externo padrão, tais como o diretórioPictures. Os aplicativos, +como aplicativos de fotografia, podem usar essas APIs em vez de +READ_EXTERNAL_STORAGE, que concede acesso a todos os diretórios de +armazenamento, ou da Estrutura de acesso ao armazenamento, que faz o usuário navegar até o diretório.

    -

    Além disso, as novas APIs simplificam as etapas executadas pelo usuário para conceder ao aplicativo +

    Além disso, as novas APIs simplificam as etapas executadas pelo usuário para conceder ao aplicativo acesso ao armazenamento externo. Quando você usa as novas APIs, o sistema usa uma IU de permissões simples que detalha claramente a qual diretório o aplicativo está solicitando acesso.

    -

    Para obter mais informações, consulte a documentação para desenvolvedores +

    Para obter mais informações, consulte a documentação para desenvolvedores Acessos a diretório com escopo.

    @@ -846,7 +846,7 @@ limite de temperatura. Esta flutuação representa um desafio para desenvolvedor

    -Para tratar estas limitações, o Android N inclui compatibilidade opcional para +Para tratar estas limitações, o Android N inclui compatibilidade opcional para modo de desempenho sustentado, permitindo que OEMs ofereçam dicas sobre capacidades de desempenho em dispositivo para aplicativos de longa duração. Os desenvolvedores de aplicativos podem usar essas dicas para ajustar os aplicativos para um nível de desempenho do dispositivo previsível @@ -869,8 +869,8 @@ O Android N adiciona compatibilidade de plataformas e otimizações para um novo desenvolvedores a capacidade de projetar experiências de RV móveis de alta qualidade para os usuários. Há diversas melhorias de desempenho , incluindo acesso a um núcleo exclusivo da CPU para aplicativos de RV. Dentro dos aplicativos, é possível tirar vantagem do rastreamento inteligente da cabeça -e de notificações estéreo que funcionam para RV. Mais importante, o Android N oferece -gráficos de latência muito baixa. Para obter informações completas sobre a criação de aplicativos de RV para Android N, +e de notificações estéreo que funcionam para RV. Mais importante, o Android N oferece +gráficos de latência muito baixa. Para obter informações completas sobre a criação de aplicativos de RV para Android N, consulte o Google VR SDK para Android.

    @@ -883,7 +883,7 @@ consulte o Google VR SDK par

    - Ao listar impressoras individuais, agora um serviço de impressão pode definir + Ao listar impressoras individuais, agora um serviço de impressão pode definir ícones por impressora de duas maneiras:

    diff --git a/docs/html-intl/intl/pt-br/preview/behavior-changes.jd b/docs/html-intl/intl/pt-br/preview/behavior-changes.jd index 1e56a9951986b..b2f07d973ff92 100644 --- a/docs/html-intl/intl/pt-br/preview/behavior-changes.jd +++ b/docs/html-intl/intl/pt-br/preview/behavior-changes.jd @@ -44,7 +44,7 @@ Visão geral da API do Android N

    - Junto com novos recursos e funcionalidades, o Android N + Junto com novos recursos e funcionalidades, o Android N inclui uma variedade de mudanças de comportamento do sistema e da API. Este documento destaca algumas das principais mudanças que você deve entender e considerar nos aplicativos. @@ -88,7 +88,7 @@ recursos do sistema, bem como a forma como ele interage com outros aplicativos p período, o dispositivo entrará no modo de soneca e aplicará o primeiro subconjunto de restrições: o acesso do aplicativo à rede será desativado e os trabalhos e sincronizações serão adiados. Se o dispositivo permanecer estacionário por um determinado período após entrar no modo soneca, o sistema aplicará -as demais restrições de soneca a {@link android.os.PowerManager.WakeLock}, aos alarmes +as demais restrições de soneca a {@link android.os.PowerManager.WakeLock}, aos alarmes {@link android.app.AlarmManager} e às verificações de GPS e Wi-Fi. Independentemente de as restrições de soneca serem aplicadas parcial ou totalmente, o sistema despertará o dispositivo para breves janelas de manutenção, quando os aplicativos @@ -151,7 +151,7 @@ do dispositivo e a experiência do usuário.

    • Os aplicativos direcionados ao Android N não receberão transmissões {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION}, mesmo - se tiverem entradas no manifesto solicitando notificação desses eventos. Os aplicativos em execução + se tiverem entradas no manifesto solicitando notificação desses eventos. Os aplicativos em execução ainda poderão escutar {@code CONNECTIVITY_CHANGE} no encadeamento principal se solicitarem a notificação com {@link android.content.BroadcastReceiver}.
    • @@ -175,7 +175,7 @@ android.app.job.JobScheduler} para reagir a mudanças em provedores de conteúdo

      Para obter mais informações sobre otimizações em segundo plano no N e como adaptar seu aplicativo, - consulte Otimizações + consulte Otimizações em segundo plano.

      @@ -245,14 +245,14 @@ ContentResolver.openFileDescriptor()}.

      Para aplicativos direcionados ao Android N, a estrutura do Android cumpre com -a política de API {@link android.os.StrictMode} que proíbe a exposição de URIs {@code file://} +a política de API {@link android.os.StrictMode} que proíbe a exposição de URIs {@code file://} fora do aplicativo. Se uma intenção que contenha o URI de um arquivo deixar o aplicativo, ele falhará com uma exceção {@code FileUriExposedException}.

      Para compartilhar arquivos entre aplicativos, você deve enviar um URI {@code content://} -e conceder uma permissão de acesso temporária ao URI. A forma mais fácil de conceder essa permissão é +e conceder uma permissão de acesso temporária ao URI. A forma mais fácil de conceder essa permissão é usar a classe {@link android.support.v4.content.FileProvider}. Para obter mais informações sobre permissões e compartilhamento de arquivos, consulte Compartilhamento de Arquivos. @@ -334,7 +334,7 @@ sw320dp, que é a largura do Nexus 4, um telefone comum de tamanho médio. rede. Verifique a ocorrência de alterações de configuração quando o aplicativo sair do estado pausado e retomar a execução.

      - Observação: se você armazenar em cache dados dependentes de configuração, + Observação: se você armazenar em cache dados dependentes de configuração, recomendamos incluir metadados relevantes, como o tamanho de tela adequado ou a densidade de pixels desses dados. Salvar esses dados permitirá que você decida se será necessário atualizar os dados armazenados em cache após uma mudança @@ -373,7 +373,7 @@ configurações ativadas. As configurações podem ser encontradas em Se

      Para alertar sobre o uso de APIs não públicas, os aplicativos executados em um dispositivo Android N geram um erro na saída logcat quando um aplicativo chama uma API não pública. - Esse erro também é exibido na tela do dispositivo como mensagem para que o usuário + Esse erro também é exibido na tela do dispositivo como mensagem para que o usuário fique ciente da situação. Revise o código do seu aplicativo para remover o uso de APIs de plataformas não públicas e faça testes completos do aplicativo usando um dispositivo de visualização ou um emulador. @@ -384,7 +384,7 @@ fique ciente da situação. Revise o código do seu aplicativo para para obter soluções usuais de substituição de APIs privadas comuns por APIs públicas equivalentes. Também é possível que você esteja vinculando bibliotecas de plataforma sem perceber, particularmente se o aplicativo usar uma biblioteca que faz parte da plataforma (como - libpng), mas não faz parte do NDK. Nesse caso, verifique se + libpng), mas não faz parte do NDK. Nesse caso, verifique se o APK contém todos os arquivos .so que você pretende vincular.

      @@ -398,9 +398,9 @@ o APK contém todos os arquivos .so que você pretende vincular. Os aplicativos não devem depender de nem usar bibliotecas nativas não incluídas no NDK, pois elas podem ser alteradas ou removidas entre uma versão do Android e outra. A mudança de OpenSSL para BoringSSL é um exemplo dessas alterações. - Além disso, dispositivos diferentes podem oferecer níveis distintos de compatibilidade, pois - não há requisitos de compatibilidade para bibliotecas de plataforma não incluídas -no NDK. Se você precisar acessar bibliotecas que não são do NDK em dispositivos mais antigos, torne o carregamento + Além disso, dispositivos diferentes podem oferecer níveis distintos de compatibilidade, pois + não há requisitos de compatibilidade para bibliotecas de plataforma não incluídas +no NDK. Se você precisar acessar bibliotecas que não são do NDK em dispositivos mais antigos, torne o carregamento dependente do nível da Android API.

      @@ -528,28 +528,28 @@ Se o seu aplicativo se baseou neste comportamento, adicione uma política de ret
      • Quando um aplicativo for executado no Android N, mas for direcionado a um nível da API menor - e o usuário alterar o tamanho da tela, o processo do aplicativo será eliminado. O aplicativo -deverá ser capaz de processar corretamente esse cenário. Caso contrário, ele falhará + e o usuário alterar o tamanho da tela, o processo do aplicativo será eliminado. O aplicativo +deverá ser capaz de processar corretamente esse cenário. Caso contrário, ele falhará quando o usuário restaurá-lo usando Recents.

        -Você deve testar o aplicativo para verificar -se esse comportamento não ocorre. -Isso pode ser feito causando uma falha idêntica +Você deve testar o aplicativo para verificar +se esse comportamento não ocorre. +Isso pode ser feito causando uma falha idêntica eliminando o aplicativo manualmente usando o DDMS.

        -Aplicativos direcionados ao Android N e versões posteriores não serão eliminados automaticamente em mudanças de densidade. +Aplicativos direcionados ao Android N e versões posteriores não serão eliminados automaticamente em mudanças de densidade. No entanto, podem continuar a responder a alterações de configurações de forma não ideal.

      • -Os aplicativos no Android N devem ser capazes de processar corretamente mudanças de configuração -e não devem falhar em inicializações subsequentes. Você pode verificar o comportamento do aplicativo +Os aplicativos no Android N devem ser capazes de processar corretamente mudanças de configuração +e não devem falhar em inicializações subsequentes. Você pode verificar o comportamento do aplicativo alterando o tamanho da fonte (Setting > -Display > Font size) e depois restaurando +Display > Font size) e depois restaurando o aplicativo em Recents.
      • @@ -557,12 +557,12 @@ o aplicativo em Recents. Devido a um erro em versões anteriores do Android, o sistema não sinaliza gravações em um soquete TCP no encadeamento principal como violações do modo estrito. O Android N corrigiu esse erro. Agora, os aplicativos que exibirem este comportamento gerarão uma{@code android.os.NetworkOnMainThreadException}. -Geralmente, a realização de operações de rede no encadeamento principal é uma má ideia porque essas operações +Geralmente, a realização de operações de rede no encadeamento principal é uma má ideia porque essas operações geralmente têm alta latência no final, causando ANRs e problemas.
      • -Agora, por padrão, a família de métodos {@code Debug.startMethodTracing()} armazena +Agora, por padrão, a família de métodos {@code Debug.startMethodTracing()} armazena os resultados no diretório específico do pacote no armazenamento compartilhado, e não no nível mais alto do cartão SD. Isso significa que os aplicativos não precisam mais solicitar a permissão {@code WRITE_EXTERNAL_STORAGE} para usar estas APIs. @@ -583,9 +583,9 @@ que faz com que {@code ActivityThread.StopInfo} gere uma Se um aplicativo publica tarefas {@link java.lang.Runnable} para uma {@link android.view.View} e esta {@link android.view.View} não está anexada a uma janela, o sistema -coloca a tarefa {@link java.lang.Runnable} em fila com a {@link android.view.View}. -A tarefa {@link java.lang.Runnable} não é executada até que a -{@link android.view.View} esteja anexada +coloca a tarefa {@link java.lang.Runnable} em fila com a {@link android.view.View}. +A tarefa {@link java.lang.Runnable} não é executada até que a +{@link android.view.View} esteja anexada a uma janela. Este comportamento corrige os seguintes erros:
        • Se um aplicativo publicasse em uma {@link android.view.View} de um encadeamento que não fosse o encadeamento de IU da janela pretendida diff --git a/docs/html-intl/intl/pt-br/preview/features/afw.jd b/docs/html-intl/intl/pt-br/preview/features/afw.jd index c16cff9f97e0c..977d2a0f968a0 100644 --- a/docs/html-intl/intl/pt-br/preview/features/afw.jd +++ b/docs/html-intl/intl/pt-br/preview/features/afw.jd @@ -101,7 +101,7 @@ ao dispositivo. Donos de perfis podem exigir que os usuários especifiquem um desafio de segurança para aplicativos em execução no perfil de trabalho. O sistema mostra o desafio de segurança quando o usuário tenta abrir qualquer aplicativo de trabalho. Se o usuário preencher corretamente o - desafio de segurança, o sistema desbloqueará e, se necessário, descriptografará o + desafio de segurança, o sistema desbloqueará e, se necessário, descriptografará o perfil de trabalho.

          @@ -126,14 +126,14 @@ android.app.admin.DevicePolicyManager#setPasswordMinimumLength setPasswordMinimumLength()}. O dono de perfil também pode definir o bloqueio de dispositivo usando a instância de {@link android.app.admin.DevicePolicyManager} retornada pelo novo método DevicePolicyManager.getParentProfileInstance() -. Além disso, donos de perfil podem personalizar a tela de credenciais do +. Além disso, donos de perfil podem personalizar a tela de credenciais do desafio de trabalho usando os novos métodos setOrganizationColor() e setOrganizationName() da classe {@link android.app.admin.DevicePolicyManager} .

          - Para obter detalhes sobre os novos métodos e constantes, consulte a + Para obter detalhes sobre os novos métodos e constantes, consulte a página de referência DevicePolicyManager na referência do N Preview SDK.

          @@ -149,7 +149,7 @@ página de referência DevicePolicyManager na tela de visão geral é ocultada. Os pacotes suspensos não são exibidos na tela de visão geral e não - podem mostrar caixas de diálogo (incluindo avisos e snackbars). Também não conseguem reproduzir + podem mostrar caixas de diálogo (incluindo avisos e snackbars). Também não conseguem reproduzir áudio nem vibrar o dispositivo.

          @@ -175,13 +175,13 @@ de trabalho. A tela de início indica que os aplicativos e widgets de trabalho n

          Always-On VPN

          - Os donos de dispositivo e perfil podem exigir que os aplicativos de trabalho se conectem sempre + Os donos de dispositivo e perfil podem exigir que os aplicativos de trabalho se conectem sempre por meio de uma VPN especificada. Se os donos definirem este requisito, o dispositivo iniciará a VPN automaticamente na inicialização.

          - Os donos podem exigir o uso de uma VPN chamando o novo + Os donos podem exigir o uso de uma VPN chamando o novo método DevicePolicyManager.setAlwaysOnVpnPackage(). Para descobrir se o dono definiu um requisito de VPN, chame o novo método DevicePolicyManager.GetAlwaysOnVpnPackage(). @@ -319,7 +319,7 @@ o registro no dispositivo usando DevicePolicyManager.setSecurityLoggingEna

          - O Android N inclui as seguintes adições de API para dar suporte a este recurso. Para + O Android N inclui as seguintes adições de API para dar suporte a este recurso. Para obter detalhes, consulte a Referência do N Preview SDK.

          @@ -353,7 +353,7 @@ obter detalhes, consulte a R

          Remoção de certificado do cliente

          - Agora, donos de perfis e dispositivos podem remover certificados de cliente que foram + Agora, donos de perfis e dispositivos podem remover certificados de cliente que foram instalados por meio do {@link android.app.admin.DevicePolicyManager#installKeyPair installKeyPair()} chamando o novo método DevicePolicyManager.removeKeyPair(). @@ -404,7 +404,7 @@ na instalação O dono do dispositivo ou perfil pode habilitar outro aplicativo para gerenciar restrições de aplicativo por meio do novo método DevicePolicyManager.setApplicationRestrictionsManagingPackage() -. O aplicativo indicado pode verificar se a permissão foi +. O aplicativo indicado pode verificar se a permissão foi concedida chamando DevicePolicyManager.isCallerApplicationRestrictionsManagingPackage().

          @@ -421,7 +421,7 @@ getApplicationRestrictions()} para quaisquer pacotes dentro daquele usuário ou

          Os usuários podem desativar as permissões de localidade para aplicativos de trabalho sem deixar de - acessar informações de localidade em seus aplicativos pessoais. Um interruptor de acesso de localidade + acessar informações de localidade em seus aplicativos pessoais. Um interruptor de acesso de localidade em separado em Location Settings permite que o usuário impeça atualizações de localização ou consultas de última localidade em aplicativos executados no perfil de trabalho.

          diff --git a/docs/html-intl/intl/pt-br/preview/features/background-optimization.jd b/docs/html-intl/intl/pt-br/preview/features/background-optimization.jd index 073fd5e5b03b9..cf4bbe9b8ff09 100644 --- a/docs/html-intl/intl/pt-br/preview/features/background-optimization.jd +++ b/docs/html-intl/intl/pt-br/preview/features/background-optimization.jd @@ -62,7 +62,7 @@ restrições:
        • Os aplicativos direcionados ao Preview não receberão transmissões {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION} se estiverem registrados para recebê-las no seu manifesto. Os aplicativos em execução ainda -poderão escutar {@code CONNECTIVITY_CHANGE} no encadeamento principal registrando um +poderão escutar {@code CONNECTIVITY_CHANGE} no encadeamento principal registrando um {@link android.content.BroadcastReceiver} em {@link android.content.Context#registerReceiver Context.registerReceiver()}.
        • @@ -111,7 +111,7 @@ poderão escutar {@code CONNECTIVITY_CHANGE} no encadeamento principal registran

          - Observação: Um {@link android.content.BroadcastReceiver} registrado em + Observação: Um {@link android.content.BroadcastReceiver} registrado em {@link android.content.Context#registerReceiver Context.registerReceiver()} continuará a receber essas transmissões enquanto o aplicativo estiver em execução.

          @@ -185,7 +185,7 @@ public static void scheduleJob(Context context) {

          - O aplicativo continuará a receber retornos de chamada até que o aplicativo encerre ou chame + O aplicativo continuará a receber retornos de chamada até que o aplicativo encerre ou chame {@link android.net.ConnectivityManager#unregisterNetworkCallback unregisterNetworkCallback()}.

          diff --git a/docs/html-intl/intl/pt-br/preview/features/data-saver.jd b/docs/html-intl/intl/pt-br/preview/features/data-saver.jd index 29c9ee46c0f60..f42b9cf2b4959 100644 --- a/docs/html-intl/intl/pt-br/preview/features/data-saver.jd +++ b/docs/html-intl/intl/pt-br/preview/features/data-saver.jd @@ -40,17 +40,17 @@ facilmente exceder o custo do próprio dispositivo. No N Developer Preview, os u

          - Quando um usuário ativa a Economia de dados em Settings e o dispositivo está + Quando um usuário ativa a Economia de dados em Settings e o dispositivo está em uma rede tarifada, o sistema bloqueia o uso de dados em segundo plano e avisa - aos aplicativos para reduzir o uso de dados no primeiro plano sempre que possível. Os usuários podem + aos aplicativos para reduzir o uso de dados no primeiro plano sempre que possível. Os usuários podem autorizar aplicativos específicos a usar dados tarifados em segundo plano, mesmo com a Economia de dados ativada.

          O N Developer Preview estende a API {@link android.net.ConnectivityManager} - para oferecer aos aplicativos uma forma de recuperar as -preferências do usuário para a Economia de dados e monitorar + para oferecer aos aplicativos uma forma de recuperar as +preferências do usuário para a Economia de dados e monitorar as mudanças de preferências. Como prática recomendada, os aplicativos devem verificar se o usuário ativou a Economia de dados e tentar limitar o uso de dados em primeiro e segundo plano. @@ -147,7 +147,7 @@ if (connMgr.isActiveNetworkMetered()) { O envio da intenção e do URI abre o aplicativo Settings e exibe as configurações de uso de dados de seu aplicativo. O usuário pode decidir então se ativará os dados em segundo plano para o aplicativo. Antes de enviar a intenção, é - prática recomendada perguntar primeiro ao usuário se ele deseja iniciar o + prática recomendada perguntar primeiro ao usuário se ele deseja iniciar o aplicativo Settings com o objetivo de ativar o uso de dados em segundo plano.

          diff --git a/docs/html-intl/intl/pt-br/preview/features/direct-boot.jd b/docs/html-intl/intl/pt-br/preview/features/direct-boot.jd index d14449f49a5d4..8f588411a6120 100644 --- a/docs/html-intl/intl/pt-br/preview/features/direct-boot.jd +++ b/docs/html-intl/intl/pt-br/preview/features/direct-boot.jd @@ -18,7 +18,7 @@ page.image=images/cards/card-nyc_2x.jpg -

          O Android N é executado em um modo seguro de inicialização direta +

          O Android N é executado em um modo seguro de inicialização direta quando o dispositivo é ligado, mas o usuário não o desbloqueia. Para isso, o sistema oferece dois locais de armazenamento para dados:

          diff --git a/docs/html-intl/intl/pt-br/preview/features/multi-window.jd b/docs/html-intl/intl/pt-br/preview/features/multi-window.jd index 77421820dde36..1a48140e0b14a 100644 --- a/docs/html-intl/intl/pt-br/preview/features/multi-window.jd +++ b/docs/html-intl/intl/pt-br/preview/features/multi-window.jd @@ -34,9 +34,9 @@ page.keywords="multi-window", "android N", "split screen", "free-form"

          Se você compilar o aplicativo com o N Preview SDK, poderá configurar como o aplicativo - processa a exibição de várias janelas. Por exemplo, você pode especificar as dimensões + processa a exibição de várias janelas. Por exemplo, você pode especificar as dimensões mínimas permitidas para a atividade. Você também pode desativar a exibição de várias janelas para - o aplicativo, garantindo que o sistema mostre o aplicativo apenas + o aplicativo, garantindo que o sistema mostre o aplicativo apenas em modo de tela inteira.

          diff --git a/docs/html-intl/intl/pt-br/preview/features/multilingual-support.jd b/docs/html-intl/intl/pt-br/preview/features/multilingual-support.jd index 072e55b58cd8f..c00eb9b9a798d 100644 --- a/docs/html-intl/intl/pt-br/preview/features/multilingual-support.jd +++ b/docs/html-intl/intl/pt-br/preview/features/multilingual-support.jd @@ -29,7 +29,7 @@ se seu aplicativo oferecer suporte a vários idiomas, você deverá garantir que esperada. Por fim, garanta que seu aplicativo possa lidar corretamente com idiomas que ele não tenha sido explicitamente projetado para suportar.

          -

          Este documento começa explicando a estratégia de resolução de recursos anterior ao +

          Este documento começa explicando a estratégia de resolução de recursos anterior ao Android N. Em seguida, ele descreve a estratégia de resolução de recursos aprimorada do Android N. Por fim, ele explica como aproveitar as vantagens do maior número de localidades para oferecer suporte a usuários multilíngues.

          @@ -215,7 +215,7 @@ não deixe de usar formatadores em vez de strings no código para números e dat

          Um bom exemplo é o árabe, cujo suporte no Android N foi expandido de uma {@code ar_EG} para 27 localidades de árabe. Essas localidades podem compartilhar a maioria dos recursos, mas algumas preferem dígitos ASCII, enquanto outras preferem dígitos nativos. Por exemplo, -quando você quer criar uma frase com uma variável em dígito, como +quando você quer criar uma frase com uma variável em dígito, como “Choose a 4 digit pin”, use formatadores como mostrado abaixo:

           format(locale, "Choose a %d-digit PIN", 4)
          diff --git a/docs/html-intl/intl/pt-br/preview/features/notification-updates.jd b/docs/html-intl/intl/pt-br/preview/features/notification-updates.jd index 72c2fe6185220..36988da09ea50 100644 --- a/docs/html-intl/intl/pt-br/preview/features/notification-updates.jd +++ b/docs/html-intl/intl/pt-br/preview/features/notification-updates.jd @@ -212,7 +212,7 @@ anexar a resposta do usuário ao histórico da entrada remota.

          Notificações empacotadas

          O Android N oferece aos desenvolvedores uma nova forma de representar - uma fila de notificações: notificações empacotadas. Essa forma é semelhante ao recurso + uma fila de notificações: notificações empacotadas. Essa forma é semelhante ao recurso Pilhas de Notificações no Android Wear. Por exemplo, se o aplicativo criar notificações para mensagens recebidas, quando mais de uma mensagem for recebida, empacote as @@ -243,8 +243,8 @@ Builder.setGroup()} para empacotar notificações semelhantes.

          sistema as agrupará automaticamente.

          -

          Para saber como adicionar notificações a um grupo, consulte -Adicionar +

          Para saber como adicionar notificações a um grupo, consulte +Adicionar cada notificação a um grupo.

          @@ -278,7 +278,7 @@ cada notificação a um grupo.

          Os exemplos de casos em que uma única notificação é preferível incluem mensagens individuais de uma única pessoa ou uma representação em lista - de itens de texto com uma única linha. Você pode usar + de itens de texto com uma única linha. Você pode usar ({@link android.app.Notification.InboxStyle InboxStyle} ou {@link android.app.Notification.BigTextStyle BigTextStyle}) para isso. @@ -354,7 +354,7 @@ Os exemplos de casos em que uma única notificação é preferível

          Para usar essa nova API, chame o método {@code setStyle()}, passando o estilo de visualização personalizada desejado.

          -

          O snippet mostra como construir um objeto de notificação personalizada com o método +

          O snippet mostra como construir um objeto de notificação personalizada com o método {@code DecoratedCustomViewStyle()}.

          @@ -370,7 +370,7 @@ Notification notification = new Notification.Builder()
           

          Estilo de mensagens

          O Android N traz uma nova API para personalização do estilo de uma notificação. - Usando a classe MessageStyle, você pode alterar vários + Usando a classe MessageStyle, você pode alterar vários rótulos exibidos na notificação, incluindo o título da conversa, mensagens adicionais e a visualização de conteúdo para a notificação.

          diff --git a/docs/html-intl/intl/pt-br/preview/features/picture-in-picture.jd b/docs/html-intl/intl/pt-br/preview/features/picture-in-picture.jd index 3a7dec491a137..4bdc54598826d 100644 --- a/docs/html-intl/intl/pt-br/preview/features/picture-in-picture.jd +++ b/docs/html-intl/intl/pt-br/preview/features/picture-in-picture.jd @@ -9,13 +9,13 @@ page.tags=androidn

          Neste documento

            -
          1. Declarar que sua atividade oferece suporte ao modo de +
          2. Declarar que sua atividade oferece suporte ao modo de imagem em imagem
          3. Alternar a atividade para o modo de imagem em imagem
          4. Lidar com a IU durante o modo de imagem em imagem
          5. -
          6. Continuar reprodução de vídeo no modo de +
          7. Continuar reprodução de vídeo no modo de imagem em imagem
          8. Usar uma única atividade de reprodução para imagem em imagem
          9. @@ -99,7 +99,7 @@ na janela do PIP.

            Alternar a atividade para o modo de imagem em imagem

            Quando precisar colocar a atividade no modo de PIP, chame -Activity.enterPictureInPictureMode(). O exemplo a seguir +Activity.enterPictureInPictureMode(). O exemplo a seguir entra no modo de PIP quando o usuário seleciona um botão dedicado ao PIP na barra de controle de uma mídia:

            @@ -146,7 +146,7 @@ public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) { }
          -

          Continuar reprodução de vídeo no modo de +

          Continuar reprodução de vídeo no modo de imagem em imagem

          Quando a atividade entra no modo de PIP, o sistema a considera @@ -177,11 +177,11 @@ imagem em imagem

          Ao navegar pelo conteúdo da tela principal de seu aplicativo, um usuário pode selecionar um novo vídeo enquanto uma atividade de reprodução de vídeo estiver em modo de PIP. Reproduza o novo - vídeo na atividade de reprodução existente em modo de tela cheia em vez de + vídeo na atividade de reprodução existente em modo de tela cheia em vez de lançar uma nova atividade que pode confundir o usuário.

          Para que uma única atividade seja usada para solicitações de reprodução de vídeo e -com o modo de PIP ativado ou desativado, conforme necessário, configure o +com o modo de PIP ativado ou desativado, conforme necessário, configure o android:launchMode da atividade para singleTask em seu manifesto.

          @@ -194,7 +194,7 @@ com o modo de PIP ativado ou desativado, conforme necessário, configure o

          Na atividade, modifique {@link android.app.Activity#onNewIntent -Activity.onNewIntent()} e processe o novo vídeo, interrompendo qualquer +Activity.onNewIntent()} e processe o novo vídeo, interrompendo qualquer reprodução existente, caso necessário.

          Práticas recomendadas

          diff --git a/docs/html-intl/intl/pt-br/preview/features/scoped-folder-access.jd b/docs/html-intl/intl/pt-br/preview/features/scoped-folder-access.jd index ef9ba6596189b..6a58d7656646b 100644 --- a/docs/html-intl/intl/pt-br/preview/features/scoped-folder-access.jd +++ b/docs/html-intl/intl/pt-br/preview/features/scoped-folder-access.jd @@ -25,7 +25,7 @@ acesso direcionado a diretórios para esses tipos de aplicativos. Por exemplo: -
        • Usar a +
        • Usar a Estrutura de acesso ao armazenamento geralmente faz com que o usuário selecione diretórios por meio de uma IU de sistema, o que é desnecessário se seu aplicativo sempre acessa o mesmo @@ -54,7 +54,7 @@ o diretório de armazenamento externo para o arquivo.

          Em volumes secundários, como cartões SD externos, passe nulo ao chamar StorageVolume.createAccessIntent() para solicitar acesso ao volume todo em vez de um diretório específico. -StorageVolume.createAccessIntent() retornará nulo se você passar +StorageVolume.createAccessIntent() retornará nulo se você passar nulo no volume principal ou se passar um nome de diretório inválido.

          @@ -80,7 +80,7 @@ acesso ao diretório Pictures.

          onActivityResult() com um código de resultado de Activity.RESULT_OK e os dados de intenção que contêm o URI. Use o URI fornecido para acessar as informações do diretório, o que é semelhante a usar URIs -retornados pela +retornados pela Estrutura de acesso ao armazenamento.

          diff --git a/docs/html-intl/intl/pt-br/preview/features/tv-recording-api.jd b/docs/html-intl/intl/pt-br/preview/features/tv-recording-api.jd index 15d22d1a8d4ff..890e1403793b8 100644 --- a/docs/html-intl/intl/pt-br/preview/features/tv-recording-api.jd +++ b/docs/html-intl/intl/pt-br/preview/features/tv-recording-api.jd @@ -123,7 +123,7 @@ os aplicativos de canais com recursos de gravação na tabela de provedor de con RecordedPrograms.Uri. Use APIs de provedores de conteúdo para ler, adicionar e excluir entradas dessa tabela.

          -

          Para saber mais sobre como trabalhar com dados de provedores de conteúdo, consulte +

          Para saber mais sobre como trabalhar com dados de provedores de conteúdo, consulte Fundamentos do provedor de conteúdo .

          diff --git a/docs/html-intl/intl/pt-br/preview/j8-jack.jd b/docs/html-intl/intl/pt-br/preview/j8-jack.jd index 504739689a092..22f4b679febf8 100644 --- a/docs/html-intl/intl/pt-br/preview/j8-jack.jd +++ b/docs/html-intl/intl/pt-br/preview/j8-jack.jd @@ -23,7 +23,7 @@ page.keywords="android N", "Java 8", "Jack"

          Para começar a usar esses recursos, primeiro faça o download e instale o Android -Studio 2.1 e o Android N Preview SDK, que inclui a +Studio 2.1 e o Android N Preview SDK, que inclui a cadeia de ferramentas Jack obrigatória e o Android Plugin for Gradle atualizado. Se você ainda não instalou o Android N Preview SDK, consulte Preparação para desenvolver para o Android N.

          diff --git a/docs/html-intl/intl/pt-br/preview/overview.jd b/docs/html-intl/intl/pt-br/preview/overview.jd index eaa3c0c1ae953..1c81f6d920b58 100644 --- a/docs/html-intl/intl/pt-br/preview/overview.jd +++ b/docs/html-intl/intl/pt-br/preview/overview.jd @@ -116,7 +116,7 @@ page.tags="preview", "developer", "android"

          - Informe problemas e dê-nos feedback usando o + Informe problemas e dê-nos feedback usando o issue tracker. Conecte-se a outros desenvolvedores na Comunidade N Developer. @@ -262,7 +262,7 @@ page.tags="preview", "developer", "android"

          - Para se inscrever no programa, acesse o site do programa beta + Para se inscrever no programa, acesse o site do programa beta do Android. Você verá uma lista de todos os dispositivos registrados em sua conta que estejam qualificados para inscrição no programa beta do Android. @@ -314,13 +314,13 @@ page.tags="preview", "developer", "android"

            -
          • Preparação para desenvolver para o +
          • Preparação para desenvolver para o Android N tem instruções passo a passo para você iniciar o trabalho.
          • Mudanças de comportamento indicam as principais áreas a serem testadas.
          • -
          • Documentação de novas APIs, incluindo uma visão geral das APIs, a -referência da +
          • Documentação de novas APIs, incluindo uma visão geral das APIs, a +referência da API disponível para download e guias de desenvolvedor detalhados sobre os recursos principais, como suporte para várias janelas, notificações agrupadas, suporte para vários idiomas e outros.
          • Exemplo de código que @@ -333,7 +333,7 @@ suporte para várias janelas, notificações agrupadas, suporte para vários idi

            Referência da API para download

            - Durante as primeiras atualizações do Preview, você pode fazer o download da + Durante as primeiras atualizações do Preview, você pode fazer o download da referência da API mais recente para a plataforma Android N como um arquivo zip separado. Esse download também inclui um relatório de diferenças que ajuda você a identificar as mudanças da API em relação à @@ -357,7 +357,7 @@ suporte para várias janelas, notificações agrupadas, suporte para vários idi

            • O Issue Tracker do N Developer Preview é o canal principal de feedback. É possível informar erros, - problemas de desempenho e feedback geral pelo issue tracker. Também é possível verificar os + problemas de desempenho e feedback geral pelo issue tracker. Também é possível verificar os erros conhecidos e encontrar etapas de resolução. Manteremos você atualizado sobre seu problema conforme ele seja avaliado e enviado para a equipe de engenharia do Android para análise.
            • @@ -374,7 +374,7 @@ suporte para várias janelas, notificações agrupadas, suporte para vários idi O N Developer Preview fornece um sistema apenas para desenvolvimento e uma biblioteca Android que não tem um nível da API padrão. Caso opte pelos comportamentos de compatibilidade para testar o aplicativo (o que é muito - recomendado), é possível destinar a versão de prévia do Android N + recomendado), é possível destinar a versão de prévia do Android N configurando o targetSdkVersion do aplicativo para “N”. diff --git a/docs/html-intl/intl/pt-br/preview/setup-sdk.jd b/docs/html-intl/intl/pt-br/preview/setup-sdk.jd index 6db456cba6bc5..9c1f035226036 100644 --- a/docs/html-intl/intl/pt-br/preview/setup-sdk.jd +++ b/docs/html-intl/intl/pt-br/preview/setup-sdk.jd @@ -41,7 +41,7 @@ compilar seu aplicativo. Caso contrário, não será preciso usar o Jack, mas ai necessário atualizar para o JDK 8 para desenvolver para a plataforma Android N, conforme descrito abaixo.

              -

              Se você já instalou o Android Studio, verifique se tem o Android +

              Se você já instalou o Android Studio, verifique se tem o Android Studio 2.1 ou superior clicando em Help > Check for Update (no Mac, Android Studio > Check for Updates).

              @@ -51,7 +51,7 @@ Studio 2.1 aqui.

              Obter o N Preview SDK

              -

              Para começar a desenvolver com as APIs do Android N, instale o +

              Para começar a desenvolver com as APIs do Android N, instale o Android N Preview SDK no Android Studio da seguinte maneira:

                @@ -77,7 +77,7 @@ Android N Preview SDK no Android Studio da seguinte maneira:

                Informações detalhadas sobre as APIs do Android N são disponibilizadas na documentação de referência do N Preview , que pode ser baixada pela tabela a seguir. - Este pacote contém uma versão off-line resumida do site de desenvolvedores do Android + Este pacote contém uma versão off-line resumida do site de desenvolvedores do Android e inclui uma referência de API atualizada para as APIs do Android N, além de um relatório das diferenças entre as APIs.

                @@ -92,7 +92,7 @@ Android N Preview SDK no Android Studio da seguinte maneira:

                n-preview-3-docs.zip MD5: 19bcfd057a1f9dd01ffbb3d8ff7b8d81
                - SHA-1: 9224bd4445cd7f653c4c294d362ccb195a2101e7 + SHA-1: 9224bd4445cd7f653c4c294d362ccb195a2101e7 @@ -131,7 +131,7 @@ não tiver a versão mais recente, baixe o JDK 8 agora mesmo.

                Para usar as APIs do Android N, seu projeto deve ser configurado da maneira apropriada.

                -

                Se planeja usar os recursos de linguagem do Java 8, consulte +

                Se planeja usar os recursos de linguagem do Java 8, consulte Recursos de linguagem do Java 8 para saber mais sobre os recursos do Java 8 com suporte e como configurar seu projeto com o compilador Jack.

                @@ -179,7 +179,7 @@ android {
                • Siga o guia para Testar em um dispositivo Android N.
                • -
                • Saiba mais sobre a plataforma Android N com +
                • Saiba mais sobre a plataforma Android N com Mudanças de comportamento e Recursos de APIs do Android N.
                • diff --git a/docs/html-intl/intl/pt-br/preview/support.jd b/docs/html-intl/intl/pt-br/preview/support.jd index 4580887b7a8b9..9ae32c89fd250 100644 --- a/docs/html-intl/intl/pt-br/preview/support.jd +++ b/docs/html-intl/intl/pt-br/preview/support.jd @@ -101,7 +101,7 @@ page.image=images/cards/card-n-support_2x.png desenvolvedores a capacidade de projetar experiências de RV móveis de alta qualidade para os usuários. Há diversas melhorias de desempenho, incluindo o acesso a um núcleo exclusivo da CPU para aplicativos de RV. Dentro dos aplicativos, é possível aproveitar o rastreamento inteligente - da cabeça e notificações estéreo que funcionam para RV. Mais importante, + da cabeça e notificações estéreo que funcionam para RV. Mais importante, o Android N oferece gráficos de latência muito baixa.

                  @@ -112,7 +112,7 @@ o Android N oferece gráficos de latência muito baixa.

                  Modo de desempenho sustentado

                  - O Android N inclui compatibilidade opcional para modo de desempenho + O Android N inclui compatibilidade opcional para modo de desempenho sustentado, permitindo que OEMs ofereçam dicas sobre capacidades de desempenho do dispositivo para aplicativos de longa duração. Desenvolvedores de aplicativos podem usar essas dicas para ajustar os aplicativos para um nível de @@ -143,7 +143,7 @@ sustentado, permitindo que OEMs ofereçam dicas sobre No Android N, o usuário pode pressionar Meta+/ para acionar uma tela de atalhos de teclado que exibe todos os atalhos disponíveis do sistema e do aplicativo em questão. Os desenvolvedores podem adicionar os próprios atalhos ou - ativar a tela de atalhos nos aplicativos. Consulte o Auxiliar de + ativar a tela de atalhos nos aplicativos. Consulte o Auxiliar de atalhos de teclado para saber mais.

                  @@ -223,7 +223,7 @@ API
                  Agora o sistema usa os metadados da atividade para decidir o modo do bloco. (Anteriormente, o modo do bloco era determinado pelo valor de retorno do - TileService.onTileAdded().) Para obter mais informações, consulte + TileService.onTileAdded().) Para obter mais informações, consulte TileService.META_DATA_ACTIVE_TILE na Referência da API, disponível para download.
                  @@ -604,7 +604,7 @@ issue tracker.

                  problemas podem aumentar com o uso prolongado. -
                • A vida útil da bateria pode regredir nesta versão em casos de uso de ligar e +
                • A vida útil da bateria pode regredir nesta versão em casos de uso de ligar e desligar a tela.
                @@ -857,7 +857,7 @@ issue tracker.

                problemas podem aumentar com o uso prolongado. -
              1. A vida útil da bateria pode regredir nesta versão em casos de uso de ligar e +
              2. A vida útil da bateria pode regredir nesta versão em casos de uso de ligar e desligar a tela.
              3. @@ -885,7 +885,7 @@ issue tracker.

                problemas podem aumentar com o uso prolongado. -
              4. A vida útil da bateria pode regredir nesta versão em casos de uso de ligar e +
              5. A vida útil da bateria pode regredir nesta versão em casos de uso de ligar e desligar a tela.
              6. @@ -966,7 +966,7 @@ issue tracker.

              7. Always on VPN
                • Se o modo Always on VPN estiver ativado, mas uma VPN não estiver disponível, os aplicativos - não especificados como exceções na política Always on se conectarão via + não especificados como exceções na política Always on se conectarão via rede comum. Exceto quando especificados como exceções na política Always on, os aplicativos deverão ficar off-line se não houver nenhuma conexão VPN disponível.
                    @@ -1124,7 +1124,7 @@ issue tracker.

                    desenvolvedor do aplicativo. -
                  • Quando o aplicativo é destinado para uma versão da plataforma Android anterior ao N, +
                  • Quando o aplicativo é destinado para uma versão da plataforma Android anterior ao N, ele pode não funcionar com avisos de tela dividida que aparecem diversas vezes.
                  • diff --git a/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/index.jd b/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/index.jd index 59120589f3f6e..ff226429e7ee1 100644 --- a/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/index.jd +++ b/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/index.jd @@ -45,7 +45,7 @@ métodos do ciclo de vida em sua atividade conforme ela fica em segundo plano (o está visível, mas a instância e seu estado permanecem intactos).

                    Dentro dos métodos de retorno de chamada do ciclo de vida, você pode declarar como a atividade deve se comportar quando o -usuário sai e retorna da atividade. Por exemplo, se estiver construindo um reprodutor de vídeos de transmissão em sequência, +usuário sai e retorna da atividade. Por exemplo, se estiver construindo um reprodutor de vídeos de transmissão em sequência, você pode pausar o vídeo e encerrar a conexão da rede quando o usuário alternar para outro aplicativo. Quando o usuário retornar, será possível reconectar a rede e permitir que ele reinicie o vídeo de onde parou.

                    @@ -55,7 +55,7 @@ android.app.Activity} recebe e como utilizá-los para que a atividade faça o qu usuário espera e não consuma recursos do sistema quando não estiver em uso.

                    Lições

                    - +
                    Iniciando uma atividade
                    Aprenda os fundamentos sobre ciclo de vida da atividade, como o usuário pode iniciar seu aplicativo e como @@ -68,5 +68,5 @@ fazer durante essas mudanças de estados.
                    Recriando uma atividade
                    Aprenda sobre o que acontece quando sua atividade é destruída e como reconstruir o estado da atividade quando necessário.
                    -
                    + diff --git a/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/pausing.jd b/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/pausing.jd index 55f772e51dfbe..9851579650a2c 100644 --- a/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/pausing.jd +++ b/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/pausing.jd @@ -8,13 +8,13 @@ trainingnavtop=true
                    - +

                    Esta lição ensina a

                    1. Pausar sua atividade
                    2. Reiniciar sua atividade
                    - +

                    Leia também

                    • Atividades @@ -31,12 +31,12 @@ trainingnavtop=true
                    -

                    Durante o uso normal do aplicativo, a atividade em primeiro plano as vezes é obstruída por outros +

                    Durante o uso normal do aplicativo, a atividade em primeiro plano as vezes é obstruída por outros componentes visuais que causam a pausa. Por exemplo, quando uma atividade - semitransparente é aberta (como uma no estilo de um diálogo), a atividade anterior pausa. Enquanto a + semitransparente é aberta (como uma no estilo de um diálogo), a atividade anterior pausa. Enquanto a atividade estiver parcialmente visível, mas não for o foco da atividade, ela permanecerá pausada.

                    -

                    No entanto, se a atividade estiver completamente obstruída e não visível, ela para (o que será +

                    No entanto, se a atividade estiver completamente obstruída e não visível, ela para (o que será discutido na próxima lição).

                    Conforme a atividade entra no estado pausado, o sistema chama o método {@link @@ -59,7 +59,7 @@ aguarda no estado Pausa (1). Se o usuário retornar à atividade enquanto ainda

                    Pausar sua atividade

                    - +

                    Quando o sistema chama {@link android.app.Activity#onPause()} para sua atividade, teoricamente significa que a atividade ainda está parcialmente visível, mas geralmente é um indício de que o usuário está saindo da atividade e logo entrará em estado Interrompido. Use diff --git a/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/recreating.jd b/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/recreating.jd index 7cb122f713efe..9746a65ceeb03 100644 --- a/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/recreating.jd +++ b/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/recreating.jd @@ -8,13 +8,13 @@ trainingnavtop=true

                    - +

                    Esta lição ensina a

                    1. Salvar o estado da atividade
                    2. Restaurar o estado da atividade
                    - +

                    Leia também

                    • Compatibilidade @@ -57,7 +57,7 @@ atividade pode conter mais informações de estado do que se deseja restaurar, c rastreiam o progresso do usuário na atividade.

                      Observação: para que o sistema Android restaure o estado das -visualizações em sua atividade, cada visualização precisa ter uma ID exclusiva, fornecido pelo atributo +visualizações em sua atividade, cada visualização precisa ter uma ID exclusiva, fornecido pelo atributo {@code android:id}.

                      @@ -105,7 +105,7 @@ public void onSaveInstanceState(Bundle savedInstanceState) { // Save the user's current game state savedInstanceState.putInt(STATE_SCORE, mCurrentScore); savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel); - + // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); } @@ -138,7 +138,7 @@ onCreate()}:

                      @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Always call the superclass first - + // Check whether we're recreating a previously destroyed instance if (savedInstanceState != null) { // Restore value of members from saved state @@ -157,12 +157,12 @@ android.app.Activity#onRestoreInstanceState onRestoreInstanceState()}, que o sis depois do método {@link android.app.Activity#onStart()}. O sistema chama {@link android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} se houver um estado salvo para ser restaurado. Portanto, não é necessário verificar se {@link android.os.Bundle} é null:

                      - +
                       public void onRestoreInstanceState(Bundle savedInstanceState) {
                           // Always call the superclass so it can restore the view hierarchy
                           super.onRestoreInstanceState(savedInstanceState);
                      -   
                      +
                           // Restore state members from saved instance
                           mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
                           mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
                      diff --git a/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/starting.jd b/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/starting.jd
                      index efe2badc149fe..4c1a9b846cc7f 100644
                      --- a/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/starting.jd
                      +++ b/docs/html-intl/intl/pt-br/training/basics/activity-lifecycle/starting.jd
                      @@ -9,7 +9,7 @@ trainingnavtop=true
                       
                       
                      - +

                      Esta lição ensina a

                      1. Entender o ciclo de vida do retorno de chamada
                      2. @@ -17,7 +17,7 @@ trainingnavtop=true
                      3. Criar uma nova instância
                      4. Destruir a atividade
                      - +

                      Leia também

                      • Atividades
                      • @@ -83,7 +83,7 @@ paisagem e retrato.
                      Д

                      Добавление элементов в строку действий

                      -

                      Фрагменты могут добавлять пункты меню в Меню вариантов операции (и, следовательно, в Строку действий), реализовав +

                      Фрагменты могут добавлять пункты меню в Меню вариантов операции (и, следовательно, в Строку действий), реализовав {@link android.app.Fragment#onCreateOptionsMenu(Menu,MenuInflater) onCreateOptionsMenu()}. Однако, чтобы этот метод мог принимать вызовы, необходимо вызывать {@link android.app.Fragment#setHasOptionsMenu(boolean) setHasOptionsMenu()} во время выполнения метода {@link @@ -639,7 +639,7 @@ android.app.Fragment#onContextItemSelected(MenuItem) onContextItemSelected()}.

                      -

                      Управление жизненным циклом фрагмента во многом аналогично управлению жизненным циклом операции. Как и +

                      Управление жизненным циклом фрагмента во многом аналогично управлению жизненным циклом операции. Как и операция, фрагмент может существовать в одном из трех состояний:

                      @@ -677,7 +677,7 @@ android.app.Fragment#onActivityCreated onActivityCreated()}. Дополните android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} во время транзакции, удаляющей фрагмент.

                      -

                      В остальном управление жизненным циклом фрагмента очень похоже на управление жизненным циклом +

                      В остальном управление жизненным циклом фрагмента очень похоже на управление жизненным циклом операции. Поэтому практические рекомендации по управлению жизненным циклом операций применимы и к фрагментам. При этом разработчику необходимо понимать, как жизненный цикл операции влияет на жизненный цикл фрагмента.

                      @@ -722,7 +722,7 @@ android.app.Activity#onCreate onCreate()}, фрагмент внутри это {@link android.app.Fragment#onActivityCreated onActivityCreated()}.

                      Когда операция переходит в состояние «возобновлена», можно свободно добавлять в нее фрагменты и удалять -их. Таким образом, жизненный цикл фрагмента может быть независимо изменен, только пока операция остается +их. Таким образом, жизненный цикл фрагмента может быть независимо изменен, только пока операция остается в состоянии «возобновлена».

                      Однако, когда операция выходит из этого состояния, продвижение фрагмента по его @@ -785,7 +785,7 @@ android.widget.FrameLayout}), либо запускается новая опе

                      Второй фрагмент, {@code DetailsFragment}, отображает краткое содержание пьесы, выбранной в списке {@code TitlesFragment}:

                      - + {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details}

                      Вспомним код класса {@code TitlesFragment}: если пользователь нажимает на пункт списка, а @@ -798,7 +798,7 @@ android.widget.FrameLayout}), либо запускается новая опе {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details_activity} - +

                      Обратите внимание, что в альбомной конфигурации эта операция самостоятельно завершается, чтобы главная операция могла принять управление и отобразить фрагмент {@code DetailsFragment} рядом с фрагментом{@code TitlesFragment}. Это может произойти, если пользователь запустит операцию {@code DetailsActivity} в книжной ориентации экрана, а diff --git a/docs/html-intl/intl/ru/guide/components/fundamentals.jd b/docs/html-intl/intl/ru/guide/components/fundamentals.jd index 181cbbdfb1077..07f001a545ad8 100644 --- a/docs/html-intl/intl/ru/guide/components/fundamentals.jd +++ b/docs/html-intl/intl/ru/guide/components/fundamentals.jd @@ -165,7 +165,7 @@ android.provider.ContactsContract.Data}), для чтения и записи с

                      Уникальной особенностью системы Android является то, что любое приложение может запустить компонент другого приложения. Например, если вы хотите дать пользователю возможность фотографировать, используя -камеру устройства, то, поскольку наверняка имеется другое приложение, которое может выполнить это действие, вместо того чтобы разработать операцию фотографирования в своем приложении, вы можете вызвать +камеру устройства, то, поскольку наверняка имеется другое приложение, которое может выполнить это действие, вместо того чтобы разработать операцию фотографирования в своем приложении, вы можете вызвать такое приложение. Вам не нужно внедрять код из приложения для камеры или даже устанавливать на него ссылку. Вместо этого вы можете просто запустить операцию фотографирования @@ -212,7 +212,7 @@ URI, указывающий на выбранный контакт).

                      содержит только строку "аккумулятор разряжен").

                      Компоненты четвертого типа – поставщики контента – сообщениями Intent не активируются. Они -активируются по запросу от {@link android.content.ContentResolver}. Процедура определения +активируются по запросу от {@link android.content.ContentResolver}. Процедура определения контента (content resolver) обрабатывает все прямые транзакции с поставщиком контента, с тем чтобы этого не пришлось делать компоненту, который выполняет транзакции с поставщиком. Вместо этого он вызывает методы для объекта {@link android.content.ContentResolver}. Это формирует слой, абстрагирующий (в целях безопасности) поставщика @@ -224,7 +224,7 @@ android.content.ContentResolver}. Это формирует слой, абстр передав объект {@link android.content.Intent} методу {@link android.content.Context#startActivity startActivity()} или {@link android.app.Activity#startActivityForResult startActivityForResult()} (если требуется, чтобы операция вернула результат).

                    • -
                    • Можно запустить службу (либо выдать работающей службе новые инструкции), +
                    • Можно запустить службу (либо выдать работающей службе новые инструкции), передав объект {@link android.content.Intent} методу {@link android.content.Context#startService startService()}. Либо можно установить привязку к службе, передав объект{@link android.content.Intent} методу {@link android.content.Context#bindService bindService()}.
                    • @@ -236,7 +236,7 @@ android.content.Context#sendStickyBroadcast sendStickyBroadcast()}. android.content.ContentProvider#query query()} для объекта {@link android.content.ContentResolver}.
                    -

                    Подробные сведения об использовании объектов Intent приведены в документе Объекты Intent и +

                    Подробные сведения об использовании объектов Intent приведены в документе Объекты Intent и фильтры объектов Intent. Более подробная информация об активации определенных компонентов также приведена в следующих документах: Операции, Службы, {@link android.content.BroadcastReceiver} и Поставщики контента.

                    @@ -312,7 +312,7 @@ href="{@docRoot}guide/topics/manifest/provider-element.html"><provider>

                    Подробные сведения о структуризации файла манифеста для приложения см. в документе Файл AndroidManifest.xml @@ -331,7 +331,7 @@ href="{@docRoot}guide/topics/manifest/provider-element.html"><provider> -

                    Система определяет компоненты, которые могут ответить на сообщение Intent, путем сравнения +

                    Система определяет компоненты, которые могут ответить на сообщение Intent, путем сравнения полученного сообщения Intent с фильтрами объектов Intent, указанными в файле манифеста других приложений, имеющихся на устройстве.

                    @@ -373,13 +373,13 @@ startActivity()}, система сможет запустить вашу опе

                    Существует огромное количество устройств, работающих под управлением Android, и не все они имеют одинаковые функциональные возможности. Чтобы ваше приложение не могло быть установлено на устройствах, в которых отсутствуют функции, необходимые приложению, важно четко определить профиль для -типов устройств, поддерживаемых вашим приложением, указав требования к аппаратному и программному обеспечению в +типов устройств, поддерживаемых вашим приложением, указав требования к аппаратному и программному обеспечению в файле манифеста. Эти объявления по большей части носят информационный характер, система их не читает. Однако их читают внешние службы, например Google Play, с целью обеспечения фильтрации для пользователей, которые ищут приложения для своих устройств.

                    Например, если вашему приложению требуется камера и оно использует API-интерфейсы из Android 2.1 (уровень API 7), -эти параметры следует объявить в файле манифеста в качестве требований следующим образом:

                    +эти параметры следует объявить в файле манифеста в качестве требований следующим образом:

                     <manifest ... >
                    @@ -390,7 +390,7 @@ startActivity()}, система сможет запустить вашу опе
                     </manifest>
                     
                    -

                    Теперь ваше приложение нельзя будет установить из Google Play на устройствах, в которых нет камеры, а также на устройствах, работающих под управлением +

                    Теперь ваше приложение нельзя будет установить из Google Play на устройствах, в которых нет камеры, а также на устройствах, работающих под управлением Android версии ниже 2.1.

                    Однако можно также объявить, что приложение использует камеру, но для его работы она не является @@ -430,7 +430,7 @@ logo.png} (сохраненный в папке {@code res/drawable/}), инст соответствующем языке.

                    Android поддерживает разные квалификаторы для соответствующих ресурсов. Квалификатор - представляет собой короткую строку, которая включается в имена каталогов ресурсов с целью + представляет собой короткую строку, которая включается в имена каталогов ресурсов с целью определения конфигурации устройства, для которой эти ресурсы следует использовать. В качестве другого примера можно сказать, что для своих операций следует создавать разные макеты, которые будут соответствовать размеру и ориентации экрана устройства. Например, когда экран устройства имеет книжную @@ -469,7 +469,7 @@ logo.png} (сохраненный в папке {@code res/drawable/}), инст

                    Совместимость устройств
                    Сведения о том, каким образом система Android работает на устройствах разных типов, и общие сведения о том, - как оптимизировать свое приложение для каждого устройства или ограничить круг устройств, на которых может быть установлено + как оптимизировать свое приложение для каждого устройства или ограничить круг устройств, на которых может быть установлено приложение.
                    Системные разрешения
                    Сведения о том, как система Android ограничивает доступ приложений к определенным API-интерфейсам с помощью системы diff --git a/docs/html-intl/intl/ru/guide/components/index.jd b/docs/html-intl/intl/ru/guide/components/index.jd index 41d5a3491bf2e..13050f262b79d 100644 --- a/docs/html-intl/intl/ru/guide/components/index.jd +++ b/docs/html-intl/intl/ru/guide/components/index.jd @@ -1,7 +1,7 @@ page.title=Компоненты приложения page.landing=true -page.landing.intro=Платформа приложений системы Android позволяет создавать функциональные и инновационные приложения с помощью набора компонентов, которые можно использовать многократно. В этом разделе рассказывается о том, как создавать компоненты, определяющие элементы структуры вашего приложения, и как связывать их воедино с помощью объектов Intent. -page.metaDescription=Платформа приложений системы Android позволяет создавать функциональные и инновационные приложения с помощью набора компонентов, которые можно использовать многократно. В этом разделе рассказывается о том, как создавать компоненты, определяющие элементы структуры вашего приложения, и как связывать их воедино с помощью объектов Intent. +page.landing.intro=Платформа приложений системы Android позволяет создавать функциональные и инновационные приложения с помощью набора компонентов, которые можно использовать многократно. В этом разделе рассказывается о том, как создавать компоненты, определяющие элементы структуры вашего приложения, и как связывать их воедино с помощью объектов Intent. +page.metaDescription=Платформа приложений системы Android позволяет создавать функциональные и инновационные приложения с помощью набора компонентов, которые можно использовать многократно. В этом разделе рассказывается о том, как создавать компоненты, определяющие элементы структуры вашего приложения, и как связывать их воедино с помощью объектов Intent. page.landing.image=images/develop/app_components.png page.image=images/develop/app_components.png @@ -11,7 +11,7 @@ page.image=images/develop/app_components.png

                    Статьи блога

                    - +

                    Использование класса DialogFragment

                    В этой статье я расскажу, как с помощью DialogFragment с использованием вспомогательной библиотеки v4 (в целях обеспечения совместимости с устройствами, работающими под управлением системы с версией ниже, чем Honeycomb) можно отобразить простое диалоговое окно редактирования и вернуть результат в вызывающую операцию с помощью интерфейса.

                    @@ -21,7 +21,7 @@ page.image=images/develop/app_components.png

                    Фрагменты для всех

                    Сегодня мы выпустили библиотеку статических элементов, которая предоставляет доступ к тому же Fragments API (а также новому классу LoaderManager и нескольким другим классам), с тем чтобы приложения, совместимые с Android 1.6 и более поздними версиями, могли использовать фрагменты для создания пользовательских интерфейсов для планшетов.

                    - +

                    Многопоточность для повышения производительности

                    Для создания быстро реагирующих приложений рекомендуется, чтобы в основном потоке пользовательского интерфейса @@ -32,7 +32,7 @@ page.image=images/develop/app_components.png

                  - +

                  Сводная информация об API-интерфейсе загрузчика

                  Имеется несколько классов и интерфейсов, которые могут использовать @@ -68,7 +68,7 @@ android.app.Fragment}.

                • {@link android.app.Fragment} для управления одним или несколькими интерфейсами {@link android.content.Loader}. Это позволяет приложению управлять длительно выполняющимися операциями вместе с жизненным циклом {@link android.app.Activity} -или {@link android.app.Fragment}; чаще всего этот класс используется с +или {@link android.app.Fragment}; чаще всего этот класс используется с {@link android.content.CursorLoader}, однако приложения могут писать свои собственные загрузчики для работы с другими типами данных.
                  @@ -129,10 +129,10 @@ android.content.ContentProvider}. Вы также можете реализов загрузки данных из другого источника;
                • реализация для {@link android.app.LoaderManager.LoaderCallbacks}. Именно здесь создаются новые загрузчики и ведется управление ссылками на существующие -загрузчики;
                • +загрузчики;
                • способ отображения данных загрузчика, например {@link android.widget.SimpleCursorAdapter};
                • -
                • источник данных, например {@link android.content.ContentProvider}, когда используется +
                • источник данных, например {@link android.content.ContentProvider}, когда используется {@link android.content.CursorLoader}.

                Запуск загрузчика

                @@ -140,11 +140,11 @@ android.widget.SimpleCursorAdapter};
              8. {@link android.app.LoaderManager} управляет одним или несколькими экземплярами {@link android.content.Loader} в {@link android.app.Activity} или {@link android.app.Fragment}. Имеется только один {@link -android.app.LoaderManager} на каждую операцию или каждый фрагмент.

                +android.app.LoaderManager} на каждую операцию или каждый фрагмент.

                {@link android.content.Loader} обычно инициализируется в методе {@link -android.app.Activity#onCreate onCreate()} операции или в методе фрагмента +android.app.Activity#onCreate onCreate()} операции или в методе фрагмента {@link android.app.Fragment#onActivityCreated onActivityCreated()}. Делается это следующим образом:

                @@ -157,13 +157,13 @@ getLoaderManager().initLoader(0, null, this);
                • уникальный идентификатор, обозначающий загрузчик. В данном примере идентификатором является 0;
                • необязательные аргументы, которые передаются загрузчику при -построении (в данном примере это null);
                • +построении (в данном примере это null);
                • реализация {@link android.app.LoaderManager.LoaderCallbacks}, которая вызывает класс {@link android.app.LoaderManager} для выдачи событий загрузчика. В данном примере локальный класс реализует интерфейс {@link android.app.LoaderManager.LoaderCallbacks}, поэтому он передает ссылку -самому себе: {@code this}.
                • +самому себе: {@code this}.

                Вызов {@link android.app.LoaderManager#initLoader initLoader()} обеспечивает инициализацию загрузчика. Возможен один из двух результатов:

                @@ -193,7 +193,7 @@ onLoadFinished
                .

                начинает загрузку и заканчивает ее при необходимости, а также поддерживает состояние загрузчика и связанного с ним контента. А это подразумевает, что вы будете редко взаимодействовать с загрузчиками напрямую (однако пример использования методов загрузчика для тонкой настройки его -поведения см. в образце кода LoaderThrottle). +поведения см. в образце кода LoaderThrottle). Для вмешательства в процесс загрузки при возникновении определенных событий обычно используются методы {@link android.app.LoaderManager.LoaderCallbacks} . Более подробные сведения об этом см. в разделе Использование обратных вызовов LoaderManager.

                @@ -343,8 +343,8 @@ public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

                Этот метод вызывается, когда состояние созданного ранее загрузчика сбрасывается, в результате чего его данные теряются. Этот обратный вызов позволяет узнать, когда данные вот-вот будут высвобождены, с тем чтобы можно было удалить свою ссылку на них.  

                -

                Данная реализация вызывает -{@link android.widget.SimpleCursorAdapter#swapCursor swapCursor()} +

                Данная реализация вызывает +{@link android.widget.SimpleCursorAdapter#swapCursor swapCursor()} со значением null:

                @@ -366,7 +366,7 @@ public void onLoaderReset(Loader<Cursor> loader) {
                 android.app.Fragment}, который отображает {@link android.widget.ListView} с
                 результатами запроса к поставщику такого контента, как контакты. Для управления запросом к поставщику используется класс {@link
                 android.content.CursorLoader}.

                - +

                Чтобы приложение могло обращаться к контактам пользователя, как показано в этом примере, в его манифесте должно присутствовать разрешение {@link android.Manifest.permission#READ_CONTACTS READ_CONTACTS}.

                diff --git a/docs/html-intl/intl/ru/guide/components/processes-and-threads.jd b/docs/html-intl/intl/ru/guide/components/processes-and-threads.jd index fd298e0d3c493..c9b7dbe62a360 100644 --- a/docs/html-intl/intl/ru/guide/components/processes-and-threads.jd +++ b/docs/html-intl/intl/ru/guide/components/processes-and-threads.jd @@ -120,7 +120,7 @@ android.content.BroadcastReceiver#onReceive onReceive()}.
                • Он содержит действие {@link android.app.Activity}, которое не находится на переднем плане, но -видно пользователю (вызван метод {@link android.app.Activity#onPause onPause()}). +видно пользователю (вызван метод {@link android.app.Activity#onPause onPause()}). Например, это может происходить, если действие на переднем плане запустило диалоговое окно, которое позволяет видеть предыдущее действие позади него.
                • @@ -142,7 +142,7 @@ android.content.Context#startService startService()}, и не попадает
                • Фоновый процесс -

                  Процесс, содержащий действия, которые не видны пользователю в настоящее время (вызван метод +

                  Процесс, содержащий действия, которые не видны пользователю в настоящее время (вызван метод {@link android.app.Activity#onStop onStop()} действия). Эти процессы не оказывают непосредственного воздействия на работу пользователя, и система может удалить их в любой момент, чтобы освободить память для процессов переднего плана, @@ -168,7 +168,7 @@ LRU (недавно использованные), чтобы процессы, компонентов, активных в процессе в текущее время. Например, если процесс содержит служебное и видимое действие, процесс считается видимым, а не служебным процессом.

                  -

                  Кроме того, уровень процесса может быть повышен, поскольку имеются другие процессы, зависимые от него. +

                  Кроме того, уровень процесса может быть повышен, поскольку имеются другие процессы, зависимые от него. Например, процесс, обслуживающий другой процесс, не может иметь уровень ниже уровня обслуживаемого процесса. Например, если поставщик контента в процессе A обслуживает клиента в процессе B или служебный процесс A связан с компонентом в процессе B, процесс A всегда считается не менее @@ -319,7 +319,7 @@ private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } - + /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { diff --git a/docs/html-intl/intl/ru/guide/components/services.jd b/docs/html-intl/intl/ru/guide/components/services.jd index 62a6a7ef9d15a..28e9daa4edb30 100644 --- a/docs/html-intl/intl/ru/guide/components/services.jd +++ b/docs/html-intl/intl/ru/guide/components/services.jd @@ -291,7 +291,7 @@ android.app.Service#onStartCommand onStartCommand()}, отдельно от ос

                • Создает рабочую очередь, которая передает намерения по одному в вашу реализацию метода {@link android.app.IntentService#onHandleIntent onHandleIntent()}, поэтому вы не должны беспокоиться относительно многопоточности.
                • -
                • Останавливает службу после обработки всех запросов запуска, поэтому вам никогда не требуется вызывать +
                • Останавливает службу после обработки всех запросов запуска, поэтому вам никогда не требуется вызывать {@link android.app.Service#stopSelf}.
                • Предоставляет реализацию метода {@link android.app.IntentService#onBind onBind()} по умолчанию, которая возвращает null.
                • @@ -668,7 +668,7 @@ android.app.Service#stopForeground stopForeground()}. Этот метод сод уделить пристальное внимание тому, как ваша служба создается и уничтожается, так как служба может работать в фоновом режиме без ведома пользователя.

                  -

                  Жизненный цикл службы от создания до уничтожения может следовать двум +

                  Жизненный цикл службы от создания до уничтожения может следовать двум разным путям:

                    diff --git a/docs/html-intl/intl/ru/guide/components/tasks-and-back-stack.jd b/docs/html-intl/intl/ru/guide/components/tasks-and-back-stack.jd index c9fdc0e069bb0..8bdb39410ce4e 100644 --- a/docs/html-intl/intl/ru/guide/components/tasks-and-back-stack.jd +++ b/docs/html-intl/intl/ru/guide/components/tasks-and-back-stack.jd @@ -29,7 +29,7 @@ parent.link=activities.html
                    1. Дизайн Android: навигация
                    2. -
                    3. Элемент манифеста +
                    4. Элемент манифеста {@code <activity>}
                    5. Экран обзора
                    @@ -43,7 +43,7 @@ parent.link=activities.html Когда пользователь выбирает сообщение, открывается новая операция для просмотра этого сообщения.

                    Операция может даже запускать операции, существующие в других приложениях на устройстве. Например, -если ваше приложение хочет отправить сообщение электронной почты, вы можете определить намерение для выполнения +если ваше приложение хочет отправить сообщение электронной почты, вы можете определить намерение для выполнения действия «отправить» и включить в него некоторые данные, например, адрес электронной почты и текст сообщения. После этого открывается операция из другого приложения, которая объявила, что она обрабатывает намерения такого типа. В этом случае намерение состоит в том, чтобы отправить сообщение электронной почты, поэтому в приложении электронной почты запускается операция «составить сообщение» (если одно намерение @@ -127,7 +127,7 @@ class="img-caption">Рисунок 3. Создается нес в своем стеке — две операции под текущей операцией. Пользователь нажимает кнопку Домой, затем запускает новое приложение из средства запуска приложений. Когда появляется главный экран, Задача A переходит -в фоновый режим. Когда запускается новое приложение, система запускает задачу для этого приложения +в фоновый режим. Когда запускается новое приложение, система запускает задачу для этого приложения (Задачу B) со своим собственным стеком операций. После взаимодействия с этим приложением пользователь снова возвращается на главный экран и выбирает изначально запущенную Задачу A. Теперь Задача A переходит на передний @@ -290,7 +290,7 @@ class="img-caption">Рисунок 3. Создается нес

                    При объявлении операции в вашем файле манифеста вы можете указать, как операция должна быть связана с задачей посредством атрибута {@code -launchMode} +launchMode} элемента {@code <activity>}.

                    Атрибут {@code @@ -351,7 +351,7 @@ android.app.Activity#onNewIntent onNewIntent()}, а не путем создан имеет задачу, работающую в фоновом режиме, эта задача переводится на передний план для обработки нового намерения.

                    -

                    И при запуске операции в новой задаче, и при запуске операции в существующей задаче, +

                    И при запуске операции в новой задаче, и при запуске операции в существующей задаче, кнопка Назад всегда возвращает пользователя к предыдущей операции. Однако, если вы запускаете операцию, которая указывает режим запуска {@code singleTask}, вся задача переводится на передний план, если экземпляр этой операции существует в фоновой задаче. В этот момент @@ -505,7 +505,7 @@ href="{@docRoot}guide/topics/manifest/activity-element.html#always">alwaysRetain href="{@docRoot}guide/topics/manifest/activity-element.html#clear">clearTaskOnLaunch

                    Если для этого атрибута установлено значение {@code "true"} в корневой операции задачи, стек очищается до корневой операции каждый раз, когда пользователь выходит из задачи -и возвращается в нее. Другими словами, этот атрибут противоположен атрибуту +и возвращается в нее. Другими словами, этот атрибут противоположен атрибуту {@code alwaysRetainTaskState}. Пользователь всегда возвращается в задачу в ее исходном состоянии, даже после кратковременного выхода из нее.
                    @@ -526,7 +526,7 @@ href="{@docRoot}guide/topics/manifest/activity-element.html#finish">finishOnTask

                    Запуск задачи

                    -

                    Вы можете сделать операцию точкой входа, назначая ей фильтр намерений со значением +

                    Вы можете сделать операцию точкой входа, назначая ей фильтр намерений со значением {@code "android.intent.action.MAIN"} в качестве указанного действия и {@code "android.intent.category.LAUNCHER"} в качестве указанной категории. Например:

                    diff --git a/docs/html-intl/intl/ru/guide/index.jd b/docs/html-intl/intl/ru/guide/index.jd index b0732722e1b85..703700b064753 100644 --- a/docs/html-intl/intl/ru/guide/index.jd +++ b/docs/html-intl/intl/ru/guide/index.jd @@ -4,7 +4,7 @@ page.title=Общие сведения о платформе Android diff --git a/docs/html-intl/intl/ru/guide/topics/manifest/manifest-intro.jd b/docs/html-intl/intl/ru/guide/topics/manifest/manifest-intro.jd index f2c5a9e035909..63d3a46c6afa2 100644 --- a/docs/html-intl/intl/ru/guide/topics/manifest/manifest-intro.jd +++ b/docs/html-intl/intl/ru/guide/topics/manifest/manifest-intro.jd @@ -31,27 +31,27 @@ page.title=Манифест приложения
                  • Он задает имя пакета Java для приложения. Это имя пакета служит уникальным идентификатором приложения.
                  • -
                  • Он описывает компоненты приложения — операции, +
                  • Он описывает компоненты приложения — операции, службы, приемники широковещательных сообщений и поставщиков контента, из которых состоит -приложение. Он содержит имена классов, которые реализуют каждый компонент, и -публикует их возможности (указывает, например, какие сообщения {@link android.content.Intent -Intent} они могут принимать). На основании этих деклараций система Android +приложение. Он содержит имена классов, которые реализуют каждый компонент, и +публикует их возможности (указывает, например, какие сообщения {@link android.content.Intent +Intent} они могут принимать). На основании этих деклараций система Android может определить, из каких компонентов состоит приложение и при каких условиях их можно запускать.
                  • -
                  • Он определяет, в каких процессах будут размещаться компоненты приложения.
                  • +
                  • Он определяет, в каких процессах будут размещаться компоненты приложения.
                  • -
                  • Он объявляет, какие разрешения должны быть выданы приложению, чтобы оно могло получить -доступ к защищенным частям API-интерфейса и взаимодействовать с другими приложениями.
                  • +
                  • Он объявляет, какие разрешения должны быть выданы приложению, чтобы оно могло получить +доступ к защищенным частям API-интерфейса и взаимодействовать с другими приложениями.
                  • -
                  • Он также объявляет разрешения, требуемые для +
                  • Он также объявляет разрешения, требуемые для взаимодействия с компонентами данного приложения.
                  • -
                  • Он содержит список классов {@link android.app.Instrumentation}, которые при выполнении приложения предоставляют -сведения о профиле и прочую информацию. Эти объявления -присутствуют в файле манифеста только во время разработки и отладки +
                  • Он содержит список классов {@link android.app.Instrumentation}, которые при выполнении приложения предоставляют +сведения о профиле и прочую информацию. Эти объявления +присутствуют в файле манифеста только во время разработки и отладки приложения и удаляются перед его публикацией.
                  • -
                  • Он объявляет минимальный уровень API-интерфейса Android, который требуется +
                  • Он объявляет минимальный уровень API-интерфейса Android, который требуется приложению.
                  • Он содержит список библиотек, с которыми должно быть связано приложение.
                  • @@ -61,12 +61,12 @@ Intent} они могут принимать). На основании этих

                    Структура файла манифеста

                    -Приведенная далее схема позволяет ознакомиться с общей структурой файла манифеста и -всеми элементами, которые могут в нем содержаться. Каждый элемент вместе со всеми своими -атрибутами, полностью описывается в отдельном файле. Для просмотра подробных -сведений о любом элементе, щелкните имя элемента на схеме, -в алфавитном списке элементов, приведенном после схемы, или -в любом другом месте, где этот элемент упоминается. +Приведенная далее схема позволяет ознакомиться с общей структурой файла манифеста и +всеми элементами, которые могут в нем содержаться. Каждый элемент вместе со всеми своими +атрибутами, полностью описывается в отдельном файле. Для просмотра подробных +сведений о любом элементе, щелкните имя элемента на схеме, +в алфавитном списке элементов, приведенном после схемы, или +в любом другом месте, где этот элемент упоминается.

                    @@ -126,9 +126,9 @@ Intent} они могут принимать).  На основании этих
                     

                    -Далее приведен список всех элементов, расположенных в алфавитном порядке, которые могут +Далее приведен список всех элементов, расположенных в алфавитном порядке, которые могут присутствовать в файле манифеста. Там могут находиться только эти элементы, а никакие другие -элементы или атрибуты добавлять нельзя. +элементы или атрибуты добавлять нельзя.

                    @@ -158,74 +158,74 @@ Intent} они могут принимать). На основании этих

                    - +

                    Соглашения о компонентах файла

                    -Ко всем элементам и атрибутам +Ко всем элементам и атрибутам из файла манифеста применяется рад соглашений и правил:

                    Элементы
                    -
                    Обязательными +
                    Обязательными являются только элементы<manifest> и -<application> -. Оба они должны присутствовать в файле манифеста, при этом указать их можно только один раз. -Большинство других элементов можно указывать по нескольку раз или не указывать вовсе — хотя по -крайней мере некоторые из них нужны, чтобы файл манифеста был сколько-нибудь +<application> +. Оба они должны присутствовать в файле манифеста, при этом указать их можно только один раз. +Большинство других элементов можно указывать по нескольку раз или не указывать вовсе — хотя по +крайней мере некоторые из них нужны, чтобы файл манифеста был сколько-нибудь информативным.

                    -Если в элементе и есть какое-то содержимое, то это другие элементы. +Если в элементе и есть какое-то содержимое, то это другие элементы. Все значения задаются с помощью атрибутов, а не как символьные данные в элементе.

                    Элементы, находящиеся на одном уровне, обычно не упорядочиваются. Например, - элементы <activity>, -<provider> и -<service> -можно указать в любой последовательности. (Элемент + элементы <activity>, +<provider> и +<service> +можно указать в любой последовательности. (Элемент <activity-alias> -является исключением из этого правила. Он должен следовать за элементом -<activity>, +является исключением из этого правила. Он должен следовать за элементом +<activity>, псевдонимом которого он является.)

                    Атрибуты
                    -
                    Формально все атрибуты являются необязательными. Однако некоторые их них +
                    Формально все атрибуты являются необязательными. Однако некоторые их них указывать необходимо, чтобы файл мог выполнять свое предназначение. В качестве руководства используйте эту -документацию. В отношении атрибутов, которые являются и вправду необязательными, в ней указывается значение, +документацию. В отношении атрибутов, которые являются и вправду необязательными, в ней указывается значение, используемое по умолчанию, или говорится, что произойдет, если такой атрибут не будет указан. -

                    За исключением некоторых атрибутов корневого элемента -<manifest> -, имена всех атрибутов должны начинаться с префикса {@code android:} — -например, {@code android:alwaysRetainTaskState}. Поскольку этот префикс является -универсальным, в документации при указании атрибутов по имени +

                    За исключением некоторых атрибутов корневого элемента +<manifest> +, имена всех атрибутов должны начинаться с префикса {@code android:} — +например, {@code android:alwaysRetainTaskState}. Поскольку этот префикс является +универсальным, в документации при указании атрибутов по имени он обычно опускается.

                    Объявление имен классов
                    -
                    Многие элементы соответствуют объектам Java, в том числе элементы для самого -приложения (элемент +
                    Многие элементы соответствуют объектам Java, в том числе элементы для самого +приложения (элемент <application> -) и основных его компонентов — операций -(<activity>), -служб -(<service>), -приемников широковещательных сообщений -(<receiver>) -и поставщиков контента -(<provider>). +) и основных его компонентов — операций +(<activity>), +служб +(<service>), +приемников широковещательных сообщений +(<receiver>) +и поставщиков контента +(<provider>).

                    -Если вы определяете подкласс, а это практически всегда делается для классов компонентов -({@link android.app.Activity}, {@link android.app.Service}, -{@link android.content.BroadcastReceiver} и {@link android.content.ContentProvider}), -выполняется это с помощью атрибута {@code name}. В состав имени должно входить -полное обозначение пакета. +Если вы определяете подкласс, а это практически всегда делается для классов компонентов +({@link android.app.Activity}, {@link android.app.Service}, +{@link android.content.BroadcastReceiver} и {@link android.content.ContentProvider}), +выполняется это с помощью атрибута {@code name}. В состав имени должно входить +полное обозначение пакета. Например, подкласс {@link android.app.Service} можно объявить следующим образом:

                    @@ -239,12 +239,12 @@ Intent} они могут принимать). На основании этих </manifest>

                -Однако его можно укоротить. Если первым символом в строке указать точку, эта -строка будет добавляться к имени пакета приложения (указанного атрибутом -package -элемента -package -). Следующее назначение является таким же, как приведенное выше: +Однако его можно укоротить. Если первым символом в строке указать точку, эта +строка будет добавляться к имени пакета приложения (указанного атрибутом +package +элемента +package +). Следующее назначение является таким же, как приведенное выше:

                <manifest package="com.example.project" . . . >
                @@ -257,13 +257,13 @@ Intent} они могут принимать).  На основании этих
                 </manifest>

                -При запуске компонента Android создает экземпляр подкласса, указанного по имени. +При запуске компонента Android создает экземпляр подкласса, указанного по имени. Если подкласс не указан, система создает экземпляр базового класса.

                Несколько значений
                -
                Если можно указать несколько значений, элемент почти всегда -приводится повторно. Делается это вместо перечисления нескольких значений в одном элементе. +
                Если можно указать несколько значений, элемент почти всегда +приводится повторно. Делается это вместо перечисления нескольких значений в одном элементе. Например, в фильтре Intent может быть перечислено несколько действий:
                <intent-filter . . . >
                @@ -274,24 +274,24 @@ Intent} они могут принимать).  На основании этих
                 </intent-filter>
                Значения ресурсов
                -
                Значения некоторых атрибутов могут отображаться на экране — например, -метка и значок операции. Значения этих атрибутов -следует локализовать, поэтому они должны задаваться в ресурсе или теме. Значения +
                Значения некоторых атрибутов могут отображаться на экране — например, +метка и значок операции. Значения этих атрибутов +следует локализовать, поэтому они должны задаваться в ресурсе или теме. Значения ресурсов выражаются в следующем формате:

                {@code @[пакет:]тип:имя}

                -где имя пакета можно опустить, если ресурс находится в одном пакете -с приложением, тип — это тип ресурса, — например "string" или -"drawable", — а имя — это имя, определяющее ресурс. +где имя пакета можно опустить, если ресурс находится в одном пакете +с приложением, тип — это тип ресурса, — например "string" или +"drawable", — а имя — это имя, определяющее ресурс. Например:

                <activity android:icon="@drawable/smallPic" . . . >

                -Значения из темы выражаются схожим образом, только в начале у них идет "{@code ?}", +Значения из темы выражаются схожим образом, только в начале у них идет "{@code ?}", а не "{@code @}":

                @@ -299,8 +299,8 @@ Intent} они могут принимать). На основании этих

                Строковые значения
                -
                Когда значением атрибута является строка, следует использовать двойную обратную косую черту ("{@code \\}") -для выделения управляющей последовательности символов, — например "{@code \\n}" для +
                Когда значением атрибута является строка, следует использовать двойную обратную косую черту ("{@code \\}") +для выделения управляющей последовательности символов, — например "{@code \\n}" для новой строки или "{@code \\uxxxx}" для символа Юникода.
                @@ -308,7 +308,7 @@ Intent} они могут принимать). На основании этих

                Отображение функций в файле

                -В следующих разделах описано, как некоторые функции Android отображаются +В следующих разделах описано, как некоторые функции Android отображаются в файле манифеста.

                @@ -316,37 +316,37 @@ Intent} они могут принимать). На основании этих

                Фильтры объектов Intent

                -Базовые компоненты приложения (его операции, службы и -приемники широковещательных сообщений) активируются объектами Intent. Intent — -это совокупность информации (объект {@link android.content.Intent}), описывающей -требуемое действие, — в том числе в ней указаны данные, с которыми следует выполнить это действие, категория -компонентов, которые должны выполнять это действие, и другие уместные инструкции. -Система Android находит компонент, который отреагирует на объект Intent, запускает -новый экземпляр компонента, если он требуется, и передает ему +Базовые компоненты приложения (его операции, службы и +приемники широковещательных сообщений) активируются объектами Intent. Intent — +это совокупность информации (объект {@link android.content.Intent}), описывающей +требуемое действие, — в том числе в ней указаны данные, с которыми следует выполнить это действие, категория +компонентов, которые должны выполнять это действие, и другие уместные инструкции. +Система Android находит компонент, который отреагирует на объект Intent, запускает +новый экземпляр компонента, если он требуется, и передает ему объект Intent.

                -Компоненты объявляют свои возможности — виды объектов Intent, на которые они могут -реагировать, — с помощью фильтров Intent. Поскольку система Android -должна узнать, какие объекты Intent может обрабатывать тот или иной компонент, до того как она его запустит, -фильтры Intent указываются в файле манифеста как -элементы <intent-filter> -. Компонент может иметь любое количество фильтров, каждый из которых описывает +Компоненты объявляют свои возможности — виды объектов Intent, на которые они могут +реагировать, — с помощью фильтров Intent. Поскольку система Android +должна узнать, какие объекты Intent может обрабатывать тот или иной компонент, до того как она его запустит, +фильтры Intent указываются в файле манифеста как +элементы <intent-filter> +. Компонент может иметь любое количество фильтров, каждый из которых описывает отдельную возможность компонента.

                -Объект Intent, в котором целевой компонент явно указан по имени, активирует этот компонент, -и фильтр при этом не учитывается. Но объект Intent, в котором имя целевого -компонента не указано, может активировать компонент, только если он может пройти через один из фильтров +Объект Intent, в котором целевой компонент явно указан по имени, активирует этот компонент, +и фильтр при этом не учитывается. Но объект Intent, в котором имя целевого +компонента не указано, может активировать компонент, только если он может пройти через один из фильтров компонента.

                -Сведения о том, каким образом объекты Intent проверяются по фильтрам Intent, -см. в отдельном документе -Объекты Intent +Сведения о том, каким образом объекты Intent проверяются по фильтрам Intent, +см. в отдельном документе +Объекты Intent и фильтры объектов Intent.

                @@ -354,42 +354,42 @@ Intent} они могут принимать). На основании этих

                Значки и метки

                -У ряда элементов есть атрибуты {@code icon} и {@code label} для -небольшого значка и текстовой метки, которые могут отображаться на экране. У некоторых из них также есть атрибут -{@code description} для более длинного описательного текста, который также может -отображаться на экране. Например, элемент +У ряда элементов есть атрибуты {@code icon} и {@code label} для +небольшого значка и текстовой метки, которые могут отображаться на экране. У некоторых из них также есть атрибут +{@code description} для более длинного описательного текста, который также может +отображаться на экране. Например, элемент <permission> -имеет все три таких атрибута, поэтому, когда пользователю задается вопрос, предоставить ли -разрешение запросившему его приложению, на экране может отображаться значок, -представляющий разрешение, имя разрешения и описание того, что оно +имеет все три таких атрибута, поэтому, когда пользователю задается вопрос, предоставить ли +разрешение запросившему его приложению, на экране может отображаться значок, +представляющий разрешение, имя разрешения и описание того, что оно за собой влечет.

                -В любом случае значок и метка, заданные в элементе-контейнере, становятся параметрами -{@code icon} и {@code label}, используемыми по умолчанию для всех вложенных в этот контейнер дочерних элементов. -Так, значок и метка, заданные в элементе -<application>, -являются значком и меткой, используемыми по умолчанию для каждого компонента приложения. -Точно так же, значок и метка, заданные для компонента, — например элемента -<activity>, — -являются параметрами, используемыми по умолчанию для каждого элемента -<intent-filter> - компонента. Если в элементе -<application> -задана метка, а в операции и ее фильтре Intent — нет, -метка приложения будет считаться меткой и для операции, и для +В любом случае значок и метка, заданные в элементе-контейнере, становятся параметрами +{@code icon} и {@code label}, используемыми по умолчанию для всех вложенных в этот контейнер дочерних элементов. +Так, значок и метка, заданные в элементе +<application>, +являются значком и меткой, используемыми по умолчанию для каждого компонента приложения. +Точно так же, значок и метка, заданные для компонента, — например элемента +<activity>, — +являются параметрами, используемыми по умолчанию для каждого элемента +<intent-filter> + компонента. Если в элементе +<application> +задана метка, а в операции и ее фильтре Intent — нет, +метка приложения будет считаться меткой и для операции, и для фильтра Intent.

                -Значок и метка, заданные для фильтра Intent, используются для обозначения компонента, +Значок и метка, заданные для фильтра Intent, используются для обозначения компонента, когда он представляется пользователю, для указания функции, -которую анонсирует фильтр. Например, фильтр с параметрами -"{@code android.intent.action.MAIN}" и -"{@code android.intent.category.LAUNCHER}" сообщает, что эта операция +которую анонсирует фильтр. Например, фильтр с параметрами +"{@code android.intent.action.MAIN}" и +"{@code android.intent.category.LAUNCHER}" сообщает, что эта операция инициирует приложение, — то есть он обозначает ее как - операцию, которая должна быть отображена в средстве запуска приложений. Отсюда следует, что значок и метка, + операцию, которая должна быть отображена в средстве запуска приложений. Отсюда следует, что значок и метка, заданные в фильтре, отображаются в средстве запуска.

                @@ -397,14 +397,14 @@ Intent} они могут принимать). На основании этих

                Разрешения

                -Разрешение представляет собой ограничение на доступ к части кода -или к данным, имеющимся на устройстве. Это ограничение накладывается для защиты важных -данных и кода, ненадлежащее использование которых может пагубно сказаться на работе приложения. +Разрешение представляет собой ограничение на доступ к части кода +или к данным, имеющимся на устройстве. Это ограничение накладывается для защиты важных +данных и кода, ненадлежащее использование которых может пагубно сказаться на работе приложения.

                -Каждое разрешение обозначается уникальной меткой. Зачастую метка обозначает -действие, выполнение которого ограничивается. Например, вот некоторые разрешения, определенные +Каждое разрешение обозначается уникальной меткой. Зачастую метка обозначает +действие, выполнение которого ограничивается. Например, вот некоторые разрешения, определенные системой Android:

                @@ -418,25 +418,25 @@ Intent} они могут принимать). На основании этих

                -Если приложению требуется доступ к функции, защищенной разрешением, -оно должно объявить, что ему необходимо это разрешение, с помощью элемента -<uses-permission> -в файле манифеста. Затем, когда приложение устанавливается на -устройство, установщик определяет, выдать ли запрошенное -разрешение, проверяя полномочия органов, подписавших сертификаты -приложения, а также, в некоторых случаях, спрашивая об этом пользователя. -Если разрешение предоставляется, приложение сможет использовать защищенные +Если приложению требуется доступ к функции, защищенной разрешением, +оно должно объявить, что ему необходимо это разрешение, с помощью элемента +<uses-permission> +в файле манифеста. Затем, когда приложение устанавливается на +устройство, установщик определяет, выдать ли запрошенное +разрешение, проверяя полномочия органов, подписавших сертификаты +приложения, а также, в некоторых случаях, спрашивая об этом пользователя. +Если разрешение предоставляется, приложение сможет использовать защищенные функции. В противном случае его попытки доступа к этим функциям будут безуспешными, -причем пользователь не получит никакого уведомления об этом. +причем пользователь не получит никакого уведомления об этом.

                -Приложение также может защищать с помощью разрешений собственные компоненты (операции, службы, -приемники широковещательных сообщений и поставщиков контента). Оно может использовать -любые разрешения, определенные системой Android (они приведены в объекте -{@link android.Manifest.permission android.Manifest.permission}) или объявленные -другими приложениями. Либо оно может определить разрешения самостоятельно. Новое разрешение объявляется -с помощью элемента +Приложение также может защищать с помощью разрешений собственные компоненты (операции, службы, +приемники широковещательных сообщений и поставщиков контента). Оно может использовать +любые разрешения, определенные системой Android (они приведены в объекте +{@link android.Manifest.permission android.Manifest.permission}) или объявленные +другими приложениями. Либо оно может определить разрешения самостоятельно. Новое разрешение объявляется +с помощью элемента <permission> . Например, операцию можно защитить следующим образом:

                @@ -457,43 +457,43 @@ Intent} они могут принимать). На основании этих

                -Обратите внимание, что в этом примере разрешение {@code DEBIT_ACCT} не только -объявляется с помощью элемента +Обратите внимание, что в этом примере разрешение {@code DEBIT_ACCT} не только +объявляется с помощью элемента <permission> -, его использование также запрашивается с помощью элемента +, его использование также запрашивается с помощью элемента <uses-permission> . Чтобы другие компоненты приложения запускали защищенную -операцию, ее использование должно быть запрошено, даже несмотря на то, что защита -наложена самим приложением. +операцию, ее использование должно быть запрошено, даже несмотря на то, что защита +наложена самим приложением.

                -В этом же примере: если атрибут {@code permission} был бы задан как -разрешение, объявленное где-то еще -(например, {@code android.permission.CALL_EMERGENCY_NUMBERS}), его бы не -нужно было объявлять еще раз с помощью элемента +В этом же примере: если атрибут {@code permission} был бы задан как +разрешение, объявленное где-то еще +(например, {@code android.permission.CALL_EMERGENCY_NUMBERS}), его бы не +нужно было объявлять еще раз с помощью элемента <permission> -. Однако все равно нужно было бы запрашивать его использование с помощью -<uses-permission>. +. Однако все равно нужно было бы запрашивать его использование с помощью +<uses-permission>.

                -Элемент -<permission-tree> -объявляет пространство имен для группы разрешений, которые будут определены в -коде. А элемент +Элемент +<permission-tree> +объявляет пространство имен для группы разрешений, которые будут определены в +коде. А элемент <permission-group> -определяет метку для набора разрешений (как для разрешений, объявленных в файле манифеста с помощью элементов +определяет метку для набора разрешений (как для разрешений, объявленных в файле манифеста с помощью элементов <permission> -, так и для объявленных где-то еще). Это влияет только на то, каким образом разрешения -группируются, когда отображаются пользователю. Элемент +, так и для объявленных где-то еще). Это влияет только на то, каким образом разрешения +группируются, когда отображаются пользователю. Элемент <permission-group> -не указывает, какие разрешения относятся к группе. +не указывает, какие разрешения относятся к группе. Он просто дает группе имя. Чтобы включить разрешение в группу, -атрибуту -permissionGroup - его элемента -<permission> +атрибуту +permissionGroup + его элемента +<permission> необходимо присвоить имя группы.

                @@ -501,17 +501,17 @@ Intent} они могут принимать). На основании этих

                Библиотеки

                -Каждое приложение связывается с используемой по умолчанию библиотекой Android, в которой -имеются базовые пакеты для построения приложений (со стандартными классами, -например Activity, Service, Intent, View, Button, Application, ContentProvider +Каждое приложение связывается с используемой по умолчанию библиотекой Android, в которой +имеются базовые пакеты для построения приложений (со стандартными классами, +например Activity, Service, Intent, View, Button, Application, ContentProvider и так далее).

                -Однако некоторые пакеты находятся в собственных библиотеках. Если ваше приложение -использует код из одного из таких пакетов, оно должно в явном виде потребовать, чтобы его связали -с этим пакетом. Файл манифеста должен содержать отдельный элемент -<uses-library> -для указания имени каждой библиотеки. (Имя библиотеки можно найти в +Однако некоторые пакеты находятся в собственных библиотеках. Если ваше приложение +использует код из одного из таких пакетов, оно должно в явном виде потребовать, чтобы его связали +с этим пакетом. Файл манифеста должен содержать отдельный элемент +<uses-library> +для указания имени каждой библиотеки. (Имя библиотеки можно найти в документации по пакету.)

                diff --git a/docs/html-intl/intl/ru/guide/topics/providers/calendar-provider.jd b/docs/html-intl/intl/ru/guide/topics/providers/calendar-provider.jd index 2d12e1261d933..3533ad00f6a19 100644 --- a/docs/html-intl/intl/ru/guide/topics/providers/calendar-provider.jd +++ b/docs/html-intl/intl/ru/guide/topics/providers/calendar-provider.jd @@ -42,7 +42,7 @@ page.title=Поставщик календаря
              9. Использование намерения для просмотра данных календаря
              10. - +
              11. Адаптеры синхронизации
              12. @@ -113,26 +113,26 @@ URI имеют формат <class>.CONTENT_URI. Н - + - + - + - + - + - +

                {@link android.provider.CalendarContract.Calendars}

                В этой таблице находится информация о календарях. В каждой строке этой таблицы представлены сведения об отдельном календаре, например, его название, цвет, информация о синхронизации и т. д.
                {@link android.provider.CalendarContract.Events}В этой таблице находится информация о событиях. В каждой строке этой таблицы содержится информация об отдельном событии —например, заголовок события, место проведения, время начала, время завершения и т. д. Событие может быть однократным или повторяющимся. Сведения об участниках, -напоминаниях и расширенные свойства хранятся в отдельных таблицах. +напоминаниях и расширенные свойства хранятся в отдельных таблицах. В каждой из них имеется целочисленная переменная {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID}, которая ссылается на объект {@link android.provider.BaseColumns#_ID} в таблице событий.
                {@link android.provider.CalendarContract.Instances}В этой таблице содержатся данные о времени начала и окончания каждого повторения события. В каждой строке этой таблицы представлено одно повторение события. Однократные события сопоставляются с повторениями @@ -141,7 +141,7 @@ URI имеют формат <class>.CONTENT_URI. Н
                {@link android.provider.CalendarContract.Attendees}В этой таблице находится информация об участниках (гостях). В каждой строке этой таблицы указан один гость. В ней указываются тип гостя и информация о том, @@ -149,7 +149,7 @@ URI имеют формат <class>.CONTENT_URI. Н
                {@link android.provider.CalendarContract.Reminders}В этой таблице находятся данные уведомлений или оповещений. В каждой строке этой таблицы указано одно уведомление или оповещение. Для одного события можно создать несколько напоминаний. Максимальное количество таких напоминаний для события @@ -159,7 +159,7 @@ URI имеют формат <class>.CONTENT_URI. Н указанным календарем. Напоминания задаются в минутах до начала события и имеют метод, который определяет порядок уведомления пользователя.

                API поставщика календаря обеспечивает достаточную гибкость и эффективность. В то же время @@ -211,7 +211,7 @@ android.Manifest.permission#READ_CALENDAR}. Также в него

                В таблице {@link android.provider.CalendarContract.Calendars} содержатся подробные сведения о каждом отдельном календаре. Выполнять запись в указанные ниже столбцы -этой таблицы могут и приложение, и адаптер синхронизации. +этой таблицы могут и приложение, и адаптер синхронизации. Полный список поддерживаемых полей представлен в справке по классу {@link android.provider.CalendarContract.Calendars}.

                @@ -229,7 +229,7 @@ android.Manifest.permission#READ_CALENDAR}. Также в него - + - + - + - + - + - - + + - + - + - + - - + - + - + @@ -514,11 +514,11 @@ java.util.TimeZone#getAvailableIDs()}. Обратите внимание, что вставке события с помощью намерения {@link android.content.Intent#ACTION_INSERT INSERT}, как описано в разделе Использование намерения для вставки события, — в этом случае используется часовой пояс по умолчанию. - +
              13. Для однократных событий необходимо указать {@link android.provider.CalendarContract.EventsColumns#DTEND}.
              14. - - + +
              15. Для повторяющихся событий необходимо указать {@link android.provider.CalendarContract.EventsColumns#DURATION} в дополнение к {@link android.provider.CalendarContract.EventsColumns#RRULE} или {@link @@ -528,7 +528,7 @@ android.content.Intent#ACTION_INSERT INSERT}, как описано в разд случае можно использовать {@link android.provider.CalendarContract.EventsColumns#RRULE} в сочетании с {@link android.provider.CalendarContract.EventsColumns#DTSTART} и {@link android.provider.CalendarContract.EventsColumns#DTEND}; кроме того, приложение «Календарь» автоматически преобразует указанный период в продолжительность.
              16. - +

                Ниже представлен пример вставки события. Для простоты все это выполняется в потоке @@ -539,8 +539,8 @@ android.provider.CalendarContract.EventsColumns#RRULE} в сочетании с

                 long calID = 3;
                -long startMillis = 0; 
                -long endMillis = 0;     
                +long startMillis = 0;
                +long endMillis = 0;
                 Calendar beginTime = Calendar.getInstance();
                 beginTime.set(2012, 9, 14, 7, 30);
                 startMillis = beginTime.getTimeInMillis();
                @@ -561,7 +561,7 @@ Uri uri = cr.insert(Events.CONTENT_URI, values);
                 
                 // get the event ID that is the last element in the Uri
                 long eventID = Long.parseLong(uri.getLastPathSegment());
                -// 
                +//
                 // ... do something with event ID
                 //
                 //
                @@ -598,7 +598,7 @@ ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); Uri updateUri = null; // The new title for the event -values.put(Events.TITLE, "Kickboxing"); +values.put(Events.TITLE, "Kickboxing"); updateUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID); int rows = getContentResolver().update(updateUri, values, null, null); Log.i(DEBUG_TAG, "Rows updated: " + rows); @@ -625,7 +625,7 @@ ContentValues values = new ContentValues(); Uri deleteUri = null; deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID); int rows = getContentResolver().delete(deleteUri, null, null); -Log.i(DEBUG_TAG, "Rows deleted: " + rows); +Log.i(DEBUG_TAG, "Rows deleted: " + rows);

                Таблица участников

                @@ -634,10 +634,10 @@ Log.i(DEBUG_TAG, "Rows deleted: " + rows); указан один участник или гость события. При вызове метода {@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} возвращается список участников для события -с заданным {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID}. +с заданным {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID}. Этот {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} должен соответствовать {@link -android.provider.BaseColumns#_ID} определенного события.

                +android.provider.BaseColumns#_ID} определенного события.

                В таблице ниже указаны поля, доступные для записи. При вставке нового участника необходимо указать все эти поля, кроме @@ -720,7 +720,7 @@ Uri uri = cr.insert(Attendees.CONTENT_URI, values);

                В каждой строке таблицы {@link android.provider.CalendarContract.Reminders} указано одно напоминание о событии. При вызове метода {@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()}возвращается список напоминаний для события -с заданным +с заданным {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID}.

                @@ -780,9 +780,9 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values); возможность запрашивать повторения событий.

                В таблице ниже перечислены некоторые из полей, которые можно запросить для экземпляра. Обратите внимание, -что часовой пояс задается параметрами -{@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} -и +что часовой пояс задается параметрами +{@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} +и {@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_INSTANCES}.

                @@ -801,18 +801,18 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values); - + - + - + @@ -820,27 +820,27 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values); - - + - +
                {@link android.provider.CalendarContract.Calendars#VISIBLE}Логическое значение, обозначающее, выбран ли календарь для отображения. Значение «0» указывает на то, что события, связанные с этим календарем, не отображаются. Значение «1» указывает на то, что события, связанные с @@ -240,7 +240,7 @@ android.provider.CalendarContract.Instances}.
                {@link android.provider.CalendarContract.CalendarColumns#SYNC_EVENTS}Логическое значение, обозначающее, следует ли синхронизировать календарь и хранить имеющиеся в нем события на устройстве. Значение «0» указывает, что не следует синхронизировать этот календарь или хранить имеющиеся в нем события на устройстве. Значение «1» указывает, что этот календарь следует синхронизировать и @@ -268,13 +268,13 @@ public static final String[] EVENT_PROJECTION = new String[] { Calendars.CALENDAR_DISPLAY_NAME, // 2 Calendars.OWNER_ACCOUNT // 3 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1; private static final int PROJECTION_DISPLAY_NAME_INDEX = 2; private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3; - + +синхронизируются.

                В следующей части примера создается запрос. С помощью выбора определяются @@ -308,38 +308,38 @@ android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL} не

                // Run query
                 Cursor cur = null;
                 ContentResolver cr = getContentResolver();
                -Uri uri = Calendars.CONTENT_URI;   
                -String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" 
                +Uri uri = Calendars.CONTENT_URI;
                +String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND ("
                                         + Calendars.ACCOUNT_TYPE + " = ?) AND ("
                                         + Calendars.OWNER_ACCOUNT + " = ?))";
                 String[] selectionArgs = new String[] {"sampleuser@gmail.com", "com.google",
                -        "sampleuser@gmail.com"}; 
                -// Submit the query and get a Cursor object back. 
                +        "sampleuser@gmail.com"};
                +// Submit the query and get a Cursor object back.
                 cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);

                В следующем разделе кода выполняется пошаговый обзор набора результатов с помощью курсора. В нем используются константы, которые были заданы в начале примера, для получения значений для каждого из полей.

                - +
                // Use the cursor to step through the returned records
                 while (cur.moveToNext()) {
                     long calID = 0;
                     String displayName = null;
                     String accountName = null;
                     String ownerName = null;
                -      
                +
                     // Get the field values
                     calID = cur.getLong(PROJECTION_ID_INDEX);
                     displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
                     accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
                     ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
                -              
                +
                     // Do something with the values...
                 
                    ...
                 }
                 
                - +

                Изменение календаря

                Чтобы обновить календарь, можно указать {@link @@ -350,7 +350,7 @@ android.provider.BaseColumns#_ID} календаря: либо в виде ид либо в качестве первого элемента выделения. Выделение должно начинаться с "_id=?", а первым аргументом selectionArg должен быть {@link -android.provider.BaseColumns#_ID} календаря. +android.provider.BaseColumns#_ID} календаря. Также для выполнения обновлений можно закодировать идентификатор в URI. В этом примере для изменения отображаемого имени календаря используется подход @@ -387,7 +387,7 @@ android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL}. в файл манифеста приложения необходимо включить разрешение {@link android.Manifest.permission#WRITE_CALENDAR}.

                -

                Выполнять запись в указанные ниже столбцы этой таблицы могут и приложение, и +

                Выполнять запись в указанные ниже столбцы этой таблицы могут и приложение, и адаптер синхронизации. Полный список поддерживаемых полей представлен в справке по классу {@link android.provider.CalendarContract.Events}.

                @@ -434,7 +434,7 @@ android.provider.CalendarContract.Events}.

                {@link android.provider.CalendarContract.EventsColumns#DURATION}Продолжительность события в формате RFC5545. Например, значение "PT1H" обозначает, что событие должно длиться один час, а значение "P2W" указывает на продолжительность @@ -444,39 +444,39 @@ android.provider.CalendarContract.Events}.

                {@link android.provider.CalendarContract.EventsColumns#ALL_DAY}Значение «1» обозначает, что это событие занимает весь день по местному часовому поясу. Значение «0» указывает на то, что это регулярное событие, которое может начаться и завершиться в любое время в течение дня.
                {@link android.provider.CalendarContract.EventsColumns#RRULE}Правило повторения для формата события. Например, "FREQ=WEEKLY;COUNT=10;WKST=SU". С другими примерами можно ознакомиться здесь.
                {@link android.provider.CalendarContract.EventsColumns#RDATE}Даты повторения события. + Даты повторения события. Обычно {@link android.provider.CalendarContract.EventsColumns#RDATE} используется вместе с {@link android.provider.CalendarContract.EventsColumns#RRULE} для определения агрегированного набора повторяющихся событий. Дополнительные сведения представлены в спецификации RFC5545.
                {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY}Если событие считается как занятое или как свободное время, доступное для планирования.
                {@link android.provider.CalendarContract.EventsColumns#GUESTS_CAN_MODIFY}
                {@link android.provider.CalendarContract.Instances#END_DAY}День окончания экземпляра по юлианскому календарю относительно часового пояса -приложения «Календарь». - +приложения «Календарь». +
                {@link android.provider.CalendarContract.Instances#END_MINUTE}Минута окончания экземпляра, вычисленная от полуночи по часовому поясу приложения «Календарь».
                {@link android.provider.CalendarContract.Instances#EVENT_ID}
                {@link android.provider.CalendarContract.Instances#START_DAY}День начала экземпляра по юлианскому календарю относительно часового пояса приложения «Календарь». + День начала экземпляра по юлианскому календарю относительно часового пояса приложения «Календарь».
                {@link android.provider.CalendarContract.Instances#START_MINUTE}Минута начала экземпляра, вычисленная от полуночи по часовому поясу -приложения «Календарь». +приложения «Календарь».

                Запрос таблицы экземпляров

                -

                Чтобы запросить таблицу экземпляров, необходимо указать промежуток времени для запроса в +

                Чтобы запросить таблицу экземпляров, необходимо указать промежуток времени для запроса в URI. В этом примере {@link android.provider.CalendarContract.Instances} получает доступ к полю {@link android.provider.CalendarContract.EventsColumns#TITLE} посредством своей реализации -интерфейса {@link android.provider.CalendarContract.EventsColumns}. +интерфейса {@link android.provider.CalendarContract.EventsColumns}. Другими словами, {@link android.provider.CalendarContract.EventsColumns#TITLE} возвращается посредством обращения к базе данных, а не путем запроса таблицы {@link @@ -853,7 +853,7 @@ public static final String[] INSTANCE_PROJECTION = new String[] { Instances.BEGIN, // 1 Instances.TITLE // 2 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_BEGIN_INDEX = 1; @@ -868,7 +868,7 @@ long startMillis = beginTime.getTimeInMillis(); Calendar endTime = Calendar.getInstance(); endTime.set(2011, 10, 24, 8, 0); long endMillis = endTime.getTimeInMillis(); - + Cursor cur = null; ContentResolver cr = getContentResolver(); @@ -883,28 +883,28 @@ ContentUris.appendId(builder, startMillis); ContentUris.appendId(builder, endMillis); // Submit the query -cur = cr.query(builder.build(), - INSTANCE_PROJECTION, - selection, - selectionArgs, +cur = cr.query(builder.build(), + INSTANCE_PROJECTION, + selection, + selectionArgs, null); - + while (cur.moveToNext()) { String title = null; long eventID = 0; - long beginVal = 0; - + long beginVal = 0; + // Get the field values eventID = cur.getLong(PROJECTION_ID_INDEX); beginVal = cur.getLong(PROJECTION_BEGIN_INDEX); title = cur.getString(PROJECTION_TITLE_INDEX); - - // Do something with the values. - Log.i(DEBUG_TAG, "Event: " + title); + + // Do something with the values. + Log.i(DEBUG_TAG, "Event: " + title); Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(beginVal); + calendar.setTimeInMillis(beginVal); DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); - Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); + Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); } } @@ -923,8 +923,8 @@ while (cur.moveToNext()) { {@link android.content.Intent#ACTION_VIEW VIEW}

                content://com.android.calendar/time/<ms_since_epoch>

                Сослаться на URI также можно с помощью -{@link android.provider.CalendarContract#CONTENT_URI CalendarContract.CONTENT_URI}. -Пример использования этого намерения представлен в разделе Использование намерений для просмотра данных календаря. +{@link android.provider.CalendarContract#CONTENT_URI CalendarContract.CONTENT_URI}. +Пример использования этого намерения представлен в разделе Использование намерений для просмотра данных календаря. Открытие календаря во время, заданное параметром <ms_since_epoch>. @@ -935,11 +935,11 @@ while (cur.moveToNext()) {

                content://com.android.calendar/events/<event_id>

                - + Сослаться на URI также можно с помощью -{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. +{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. Пример использования этого намерения представлен в разделе Использование намерений для просмотра данных календаря. - + Просмотр события, указанного с помощью <event_id>. @@ -952,12 +952,12 @@ while (cur.moveToNext()) { {@link android.content.Intent#ACTION_EDIT EDIT}

                content://com.android.calendar/events/<event_id>

                - + Сослаться на URI также можно с помощью -{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. +{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. Пример использования этого намерения представлен в разделе Использование намерения для редактирования события. - - + + Редактирование события, указанного с помощью <event_id>. @@ -972,11 +972,11 @@ while (cur.moveToNext()) {
                {@link android.content.Intent#ACTION_INSERT INSERT}

                content://com.android.calendar/events

                - + Сослаться на URI также можно с помощью -{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. +{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. Пример использования этого намерения представлен в разделе Использование намерения для редактирования события. - + Создание события. @@ -996,7 +996,7 @@ while (cur.moveToNext()) { Название события. - + {@link android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME} Время начала события (в миллисекундах) от эпохи. @@ -1004,25 +1004,25 @@ CalendarContract.EXTRA_EVENT_BEGIN_TIME} {@link android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME} - + Время окончания события (в миллисекундах) от эпохи. {@link android.provider.CalendarContract#EXTRA_EVENT_ALL_DAY CalendarContract.EXTRA_EVENT_ALL_DAY} - + Логическое значение, обозначающее, что это событие на весь день. Значение может быть true или false. {@link android.provider.CalendarContract.EventsColumns#EVENT_LOCATION Events.EVENT_LOCATION} - + Место проведения события. {@link android.provider.CalendarContract.EventsColumns#DESCRIPTION Events.DESCRIPTION} - + Описание события. @@ -1039,16 +1039,16 @@ Events.DESCRIPTION} {@link android.provider.CalendarContract.EventsColumns#ACCESS_LEVEL Events.ACCESS_LEVEL} - + Указывает на то, является ли событие общедоступным или закрытым. {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY Events.AVAILABILITY} - + Если событие считается как занятое или как свободное время, доступное для планирования. - - + +

                В разделах ниже указан порядок использования этих намерений.

                @@ -1059,14 +1059,14 @@ Events.AVAILABILITY} Благодаря этому в файл манифеста вашего приложения не нужно включать разрешение {@link android.Manifest.permission#WRITE_CALENDAR}.

                - +

                Когда пользователи работают с приложением, в котором используется такой подход, приложение отправляет их в «Календарь» для завершения добавления события. Намерение {@link android.content.Intent#ACTION_INSERT INSERT} использует дополнительные поля для предварительного указания в форме сведений о событии в приложении «Календарь». После этого пользователи могут отменить событие, отредактировать форму или сохранить событие в своем календаре.

                - +

                Ниже представлен фрагмент кода, в котором на 19 января 2012 г. планируется событие, которое будет проходить с @@ -1075,7 +1075,7 @@ android.content.Intent#ACTION_INSERT INSERT} использует дополни

                • В качестве URI в нем задается {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}.
                • - +
                • В нем используются дополнительные поля {@link android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME} и {@link @@ -1083,10 +1083,10 @@ android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME} для предварительного указания в форме сведений о времени события. Значения времени должны быть указаны в формате UTC и в миллисекундах от эпохи.
                • - +
                • В нем используется дополнительное поле {@link android.content.Intent#EXTRA_EMAIL Intent.EXTRA_EMAIL} для предоставления списка участников, разделенных запятыми (их адреса эл. почты).
                • - +
                 Calendar beginTime = Calendar.getInstance();
                @@ -1158,12 +1158,12 @@ startActivity(intent);
                 
                 
                • Адаптеру синхронизации необходимо указать, что он является таковым, задав для параметра {@link android.provider.CalendarContract#CALLER_IS_SYNCADAPTER} значение true.
                • - - + +
                • Адаптеру синхронизации необходимо предоставить {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_NAME} и {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_TYPE} в качестве параметров запроса в URI.
                • - +
                • Адаптер синхронизации имеет доступ на запись к большему числу столбцов, чем приложение или виджет. Например, приложение может изменять только некоторые характеристики календаря, такие как название, отображаемое имя, настройки видимости и diff --git a/docs/html-intl/intl/ru/guide/topics/providers/contacts-provider.jd b/docs/html-intl/intl/ru/guide/topics/providers/contacts-provider.jd index 4d07856f250ed..151f75bc7e833 100644 --- a/docs/html-intl/intl/ru/guide/topics/providers/contacts-provider.jd +++ b/docs/html-intl/intl/ru/guide/topics/providers/contacts-provider.jd @@ -467,7 +467,7 @@ Email.CONTENT_ITEM_TYPE}, в которой в столбце

                  При добавлении нового необработанного контакта, -который не соответствует ни одному из существующих контактов, поставщик контактов создает новый контакт. Поставщик поступает аналогично в случае, если +который не соответствует ни одному из существующих контактов, поставщик контактов создает новый контакт. Поставщик поступает аналогично в случае, если данные в строке существующего необработанного контакта изменяются таким образом, что они больше не соответствуют контакту, с которым они ранее были связаны. При создании приложением или адаптером синхронизации нового контакта, который соответствует существующему контакту, то новый контакт объединяется с @@ -543,7 +543,7 @@ Email.CONTENT_ITEM_TYPE}, в которой в столбце

                  Если необходимо передать данные из службы в поставщик контактов, необходимо создать -собственный адаптер синхронизации. Дополнительные сведения об этом представлены в разделе +собственный адаптер синхронизации. Дополнительные сведения об этом представлены в разделе Адаптеры синхронизации поставщика контактов.

                  @@ -672,7 +672,7 @@ mProfileCursor = Android.

                  Адаптеры синхронизации, которые вносят изменения в необработанные контакты или таблицы данных, должны всегда добавлять к используемому ими URI -контента строку +контента строку {@link android.provider.ContactsContract#CALLER_IS_SYNCADAPTER}. Это позволяет предотвратить пометку таких строк поставщиком как «грязных». В противном случае изменения, внесенные адаптером синхронизации, будут рассматриваться как локальные изменения, которые подлежат отправке на сервер, даже если источником таких изменений был сам сервер. @@ -1809,7 +1809,7 @@ URI веб-службы для синхронизации с поставщик

                • Необязательно: элемент <meta-data> -для структуры проверки подлинности указывает на файл XML +для структуры проверки подлинности указывает на файл XML res/xml/authenticator.xml. В свою очередь, в этом файле задается тип аккаунта, который поддерживает структура проверки подлинности, а также ресурсы пользовательского интерфейса, которые отображаются в процессе аутентификации. Тип аккаунта, указанный в этом @@ -2022,7 +2022,7 @@ openAssetFileDescriptor()}, передав в него этот URI, чтобы

                Регулярная синхронизация элементов потока с помощью поставщика контактов выполняется так же, -как и любая другая синхронизация. Дополнительные сведения о синхронизации представлены в разделе +как и любая другая синхронизация. Дополнительные сведения о синхронизации представлены в разделе Адаптеры синхронизации поставщика контактов. Регистрация уведомлений и приглашение контактов рассматриваются в следующих двух разделах.

                @@ -2092,7 +2092,7 @@ openAssetFileDescriptor()}, передав в него этот URI, чтобы

                Взаимодействие со службой социальной сети

                Пользователям не обязательно выходить из приложения для работы с контактами, которое имеется на устройстве, чтобы пригласить контакт на сайт -социальной сети. Вместо этого приложение для работы с контактами может отправить намерение для приглашения +социальной сети. Вместо этого приложение для работы с контактами может отправить намерение для приглашения контакта в одну из ваших операций. Для этого выполните указанные ниже действия.

                  diff --git a/docs/html-intl/intl/ru/guide/topics/providers/content-provider-basics.jd b/docs/html-intl/intl/ru/guide/topics/providers/content-provider-basics.jd index c912dbc037523..4d520e814dc03 100644 --- a/docs/html-intl/intl/ru/guide/topics/providers/content-provider-basics.jd +++ b/docs/html-intl/intl/ru/guide/topics/providers/content-provider-basics.jd @@ -251,7 +251,7 @@ mCursor = getContentResolver().query(

                В таблице 2 указано соответствие аргументов для метода -{@link android.content.ContentResolver#query +{@link android.content.ContentResolver#query query(Uri,projection,selection,selectionArgs,sortOrder)} SQL-инструкции SELECT.

                @@ -701,7 +701,7 @@ if (mCursor != null) { для вставки, обновления или удаления данных.

                - Чтобы получить разрешения, необходимые для доступа к поставщику, приложение запрашивает их с помощью элемента + Чтобы получить разрешения, необходимые для доступа к поставщику, приложение запрашивает их с помощью элемента <uses-permission> в файле манифеста. При установке менеджером пакетов Android приложения пользователю необходимо утвердить все разрешения, запрашиваемые приложением. В случае утверждения всех разрешений diff --git a/docs/html-intl/intl/ru/guide/topics/providers/content-provider-creating.jd b/docs/html-intl/intl/ru/guide/topics/providers/content-provider-creating.jd index d8f787393eaad..d6697579b4a40 100644 --- a/docs/html-intl/intl/ru/guide/topics/providers/content-provider-creating.jd +++ b/docs/html-intl/intl/ru/guide/topics/providers/content-provider-creating.jd @@ -485,7 +485,7 @@ public class ExampleProvider extends ContentProvider {

                Необходимые методы

                В абстрактном классе {@link android.content.ContentProvider} определены шесть абстрактных методов, -которые необходимо реализовать в рамках вашего собственного конкретного подкласса. Все указанные ниже методы, кроме +которые необходимо реализовать в рамках вашего собственного конкретного подкласса. Все указанные ниже методы, кроме {@link android.content.ContentProvider#onCreate() onCreate()}, вызываются клиентским приложением, которое пытается получить доступ к вашему поставщику контента.

                @@ -777,7 +777,7 @@ URI контента. Аргумент {@link android.net.Uri} может выс

                Для общих типов данных, таких как текст, HTML или JPEG, метод {@link android.content.ContentProvider#getType(Uri) getType()} должен возвращать стандартный тип -MIME. Полный список стандартных типов представлен на +MIME. Полный список стандартных типов представлен на веб-сайте IANA MIME Media Types.

                @@ -870,8 +870,8 @@ ContentProvider.getStreamTypes()} при этом должен возвраща

                Класс-контракт представляет собой класс public final, в котором содержатся определения констант для URI, имен столбцов, типов MIME и других метаданных поставщика. Класс -устанавливает контрактные отношения между поставщиком и другими приложениями путем обеспечения -прямого доступа к поставщику даже в случае изменения фактических значений URI, имен столбцов и +устанавливает контрактные отношения между поставщиком и другими приложениями путем обеспечения +прямого доступа к поставщику даже в случае изменения фактических значений URI, имен столбцов и т. д.

                @@ -928,7 +928,7 @@ Eclipse, могут автоматически заполнять имена к

                Реализация разрешений

                Любое приложение может выполнять чтение данных в поставщике или записывать их, даже если соответствующие данные -являются закрытыми, поскольку по умолчанию для поставщика не заданы разрешения. Чтобы изменить эти настройки, +являются закрытыми, поскольку по умолчанию для поставщика не заданы разрешения. Чтобы изменить эти настройки, задайте разрешения для поставщика в файле манифеста с помощью атрибутов элемента <provider> или его дочерних элементов. Можно задать разрешения, которые применяются ко всему поставщику diff --git a/docs/html-intl/intl/ru/guide/topics/providers/document-provider.jd b/docs/html-intl/intl/ru/guide/topics/providers/document-provider.jd index c594968490d4b..c394e60cbcb3c 100644 --- a/docs/html-intl/intl/ru/guide/topics/providers/document-provider.jd +++ b/docs/html-intl/intl/ru/guide/topics/providers/document-provider.jd @@ -567,7 +567,7 @@ SAF, написав собственный поставщик документо

              17. Атрибут android:exported, установленный в значение "true". Необходимо экспортировать поставщик, чтобы он был виден другим приложениям.
              18. -
              19. Атрибут android:grantUriPermissions, установленный в значение +
              20. Атрибут android:grantUriPermissions, установленный в значение "true". Этот параметр позволяет системе предоставлять другим приложениям доступ к контенту поставщика. Обсуждение того, как следует удерживать права доступа к конкретному документу см. в разделе Удержание прав доступа.
              21. @@ -776,7 +776,7 @@ public Cursor queryRoots(String[] projection) throws FileNotFoundException {

                Реализация метода queryChildDocuments

                -

                Реализация метода +

                Реализация метода {@link android.provider.DocumentsProvider#queryChildDocuments queryChildDocuments()} должна возвращать объект{@link android.database.Cursor}, указывающий на все файлы в заданном каталоге, используя столбцы, определенные в diff --git a/docs/html-intl/intl/ru/guide/topics/resources/accessing-resources.jd b/docs/html-intl/intl/ru/guide/topics/resources/accessing-resources.jd index 3d59ceb292a24..ccb7ad8f46f02 100644 --- a/docs/html-intl/intl/ru/guide/topics/resources/accessing-resources.jd +++ b/docs/html-intl/intl/ru/guide/topics/resources/accessing-resources.jd @@ -209,7 +209,7 @@ R.java} вручную — этот файл создается инстр

                • {@code <package_name>} — это имя пакета, в котором находится ресурс (не требуется при создании ссылок на ресурсы из одного и того же пакета).
                • -
                • {@code <resource_type>} — это подкласс +
                • {@code <resource_type>} — это подкласс {@code R} для типа ресурса.
                • {@code <resource_name>} — это либо имя файла ресурса (без расширения), либо значение атрибута {@code android:name} в элементе XML (для простых @@ -222,7 +222,7 @@ R.java} вручную — этот файл создается инстр

                  Примеры использования

                  -

                  В некоторых случаях ресурс необходимо использовать в качестве значения в элементе XML (например, чтобы применить графическое изображение к +

                  В некоторых случаях ресурс необходимо использовать в качестве значения в элементе XML (например, чтобы применить графическое изображение к виджету), однако вы также можете использовать ресурс в любом фрагменте XML, где ожидается простое значение. Например, если имеется следующий файл ресурса, включающий цветовой ресурс и строковый ресурс:

                  @@ -260,13 +260,13 @@ R.java} вручную — этот файл создается инстр

                  Примечание. Всегда используйте строковые ресурсы, -поскольку ваше приложение может потребоваться перевести на другие языки. +поскольку ваше приложение может потребоваться перевести на другие языки. Сведения о создании альтернативных ресурсов (например, локализованных строк) представлены в разделе Предоставление альтернативных ресурсов. В разделе Локализация приведено полное руководство по локализации приложения.

                  -

                  Вы даже можете использовать ресурсы в XML для создания псевдонимов. Например, можно создать +

                  Вы даже можете использовать ресурсы в XML для создания псевдонимов. Например, можно создать элемент дизайна, который будет служить псевдонимом для другого элемента дизайна:

                  diff --git a/docs/html-intl/intl/ru/guide/topics/resources/providing-resources.jd b/docs/html-intl/intl/ru/guide/topics/resources/providing-resources.jd
                  index be0af952896e4..6a287b8972aaf 100644
                  --- a/docs/html-intl/intl/ru/guide/topics/resources/providing-resources.jd
                  +++ b/docs/html-intl/intl/ru/guide/topics/resources/providing-resources.jd
                  @@ -495,7 +495,7 @@ android.content.res.Configuration#smallestScreenWidthDp}, которое сод
                   экрану VGA средней плотности.
                           Минимальный размер макета для большого экрана составляет приблизительно 480x640 пикселов.
                           Примерами являются экраны VGA и WVGA средней плотности.
                • -
                • {@code xlarge}: Экраны значительно крупнее обычного +
                • {@code xlarge}: Экраны значительно крупнее обычного экрана HVGA средней плотности. Минимальный размер макета для очень большого экрана составляет приблизительно 720x960 пикселов. В большинстве случаев устройства с очень большими экранами слишком велики для карманного использования и, скорее всего, @@ -510,7 +510,7 @@ android.content.res.Configuration#smallestScreenWidthDp}, которое сод аварийно завершится во время выполнения (например, если все ресурсы макета отмечены квалификатором {@code xlarge}, но устройство оснащено экраном нормального размера).

                  Добавлено в API уровня 4.

                  - +

                  Дополнительную информацию см. в разделе Поддержка нескольких экранов.

                  См. также поле конфигурации {@link android.content.res.Configuration#screenLayout}, которое @@ -1088,7 +1088,7 @@ drawable-en-port/ чем число квалификаторов, которые точно соответствуют устройству. Например, на шаге 4 выше, последний вариант в списке содержит три квалификатора, которые точно соответствуют устройству (ориентация, тип сенсорного экрана и способ ввода), в то время как drawable-en содержит только один подходящий параметр -(язык). Однако язык имеет более высокий приоритет, чем эти остальные квалификаторы, поэтому +(язык). Однако язык имеет более высокий приоритет, чем эти остальные квалификаторы, поэтому drawable-port-notouch-12key вычеркивается.

                  Для получения более подробной информации об использовании ресурсов в приложении перейдите к разделу Доступ к ресурсам.

                  diff --git a/docs/html-intl/intl/ru/guide/topics/resources/runtime-changes.jd b/docs/html-intl/intl/ru/guide/topics/resources/runtime-changes.jd index 5dc59c81559ff..51337514566b4 100644 --- a/docs/html-intl/intl/ru/guide/topics/resources/runtime-changes.jd +++ b/docs/html-intl/intl/ru/guide/topics/resources/runtime-changes.jd @@ -125,7 +125,7 @@ android.graphics.drawable.Drawable}, {@link android.widget.Adapter}, {@link andr означает, что приложение удерживает их, и система не может очистить от них память, поэтому может теряться значительный объем памяти).

                  -

                  Затем используйте {@link android.app.FragmentManager} для добавления фрагмента в операцию. +

                  Затем используйте {@link android.app.FragmentManager} для добавления фрагмента в операцию. Можно получить объект данных из фрагмента, когда операция повторно запускается в результате изменения конфигурации в режиме выполнения. В качестве примера операция определена следующим образом:

                  @@ -168,7 +168,7 @@ public class MyActivity extends Activity {

                  В этом примере {@link android.app.Activity#onCreate(Bundle) onCreate()} добавляет фрагмент или восстанавливает ссылку на него. Метод {@link android.app.Activity#onCreate(Bundle) onCreate()} также хранит объект, сохраняющий состояние, внутри экземпляра фрагмента. -Метод {@link android.app.Activity#onDestroy() onDestroy()} обновляет объект, сохраняющий состояние, внутри +Метод {@link android.app.Activity#onDestroy() onDestroy()} обновляет объект, сохраняющий состояние, внутри сохраненного экземпляра фрагмента.

                  diff --git a/docs/html-intl/intl/ru/guide/topics/ui/controls.jd b/docs/html-intl/intl/ru/guide/topics/ui/controls.jd index 62f4c76686f5e..7e15a72c3e958 100644 --- a/docs/html-intl/intl/ru/guide/topics/ui/controls.jd +++ b/docs/html-intl/intl/ru/guide/topics/ui/controls.jd @@ -69,7 +69,7 @@ Android. Все они имеются в пакете {@link android.widget}. Е Переключатель Этот элемент управления аналогичен флажку, за исключением того, что в группе элементов можно выбрать только один вариант. - {@link android.widget.RadioGroup RadioGroup} + {@link android.widget.RadioGroup RadioGroup}
                  {@link android.widget.RadioButton RadioButton} diff --git a/docs/html-intl/intl/ru/guide/topics/ui/declaring-layout.jd b/docs/html-intl/intl/ru/guide/topics/ui/declaring-layout.jd index 71428f6e1cdd4..b5db656d0e603 100644 --- a/docs/html-intl/intl/ru/guide/topics/ui/declaring-layout.jd +++ b/docs/html-intl/intl/ru/guide/topics/ui/declaring-layout.jd @@ -219,9 +219,9 @@ LayoutParams также включают дополнительные парам

                  Как правило, не рекомендуется задавать абсолютные значения ширины и высоты макета (например, в пикселах). Вместо этого используйте относительные единицы измерения, такие как пикселы, не зависящие от разрешения экрана (dp), wrap_contentили -match_parentЭто гарантирует одинаковое отображение +match_parentЭто гарантирует одинаковое отображение вашего приложения на устройствах с экранами разных размеров. -Принятые типы измерения определены в +Принятые типы измерения определены в документе Доступные ресурсы.

                  @@ -325,7 +325,7 @@ div.layout.first { Android.

                  Примечание. Несмотря на то, что для формирования пользовательского интерфейса один -макет может содержать один или несколько вложенных макетов, рекомендуется использовать как можно более простую +макет может содержать один или несколько вложенных макетов, рекомендуется использовать как можно более простую иерархию макетов. Чем меньше в макете вложенных элементов, тем быстрее выполняется его отрисовка (горизонтальная иерархия представлений намного лучше вертикальной).

                  diff --git a/docs/html-intl/intl/ru/guide/topics/ui/dialogs.jd b/docs/html-intl/intl/ru/guide/topics/ui/dialogs.jd index 515ecc6a0130d..7e5d9087894f4 100644 --- a/docs/html-intl/intl/ru/guide/topics/ui/dialogs.jd +++ b/docs/html-intl/intl/ru/guide/topics/ui/dialogs.jd @@ -32,7 +32,7 @@ page.tags=alertdialog,dialogfragment
                • {@link android.app.DialogFragment}
                • {@link android.app.AlertDialog}
              - +

              См. также:

              1. Руководство по дизайну диалоговых окон
              2. @@ -235,8 +235,8 @@ AlertDialog dialog = builder.create();

                Методы set...Button() предполагают заголовок для кнопки (реализуемый -через строковый ресурс) и -{@link android.content.DialogInterface.OnClickListener}, который определяет действие, +через строковый ресурс) и +{@link android.content.DialogInterface.OnClickListener}, который определяет действие, следующее за нажатием кнопки пользователем.

                Реализована возможность добавлять три различных вида кнопок действий:

                @@ -248,7 +248,7 @@ AlertDialog dialog = builder.create();
                Нейтральные
                Используются в случаях, когда пользователь может не желать продолжить действие, но при этом необязательно хочет его отменить. Появляется между положительными и отрицательнымиI - кнопками. Примером такого действия может быть «Напомнить позже».
                + кнопками. Примером такого действия может быть «Напомнить позже».

                Можно добавлять только одну кнопку каждого вида в {@link @@ -271,7 +271,7 @@ android.app.AlertDialog}. Это означает, что нельзя испо

              3. Интерактивный список с выбором нескольких вариантов (флажки)
            -

            Для создания списка с выбором одного варианта, как на рисунке 3, +

            Для создания списка с выбором одного варианта, как на рисунке 3, используйте метод{@link android.app.AlertDialog.Builder#setItems setItems()}:

            @@ -289,9 +289,9 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
             }
             
            -

            Поскольку список отображается в области содержимого диалогового окна, +

            Поскольку список отображается в области содержимого диалогового окна, диалоговое окно не может показать одновременно сообщение и список, поэтому необходимо задать заголовок -диалогового окна с помощью {@link android.app.AlertDialog.Builder#setTitle setTitle()}. +диалогового окна с помощью {@link android.app.AlertDialog.Builder#setTitle setTitle()}. Для указания элементов списка необходимо вызвать {@link android.app.AlertDialog.Builder#setItems setItems()}, передающий указатель. В качестве другого варианта можно указать список с помощью {@link @@ -320,8 +320,8 @@ android.app.AlertDialog.Builder#setAdapter setAdapter()}. Наполнение

            Для добавления списка с несколькими вариантами ответов (флажки) или списка с одним вариантом ответа (переключатели) используйте методы {@link android.app.AlertDialog.Builder#setMultiChoiceItems(Cursor,String,String, -DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} или -{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} или +{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()} соответственно.

            Например, таким образом можно создать список с несколькими вариантами ответов, как на @@ -346,7 +346,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { // If the user checked the item, add it to the selected items mSelectedItems.add(which); } else if (mSelectedItems.contains(which)) { - // Else, if the item is already in the array, remove it + // Else, if the item is already in the array, remove it mSelectedItems.remove(Integer.valueOf(which)); } } @@ -371,9 +371,9 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { } -

            Несмотря на то, что и традиционный список, и список с переключателями +

            Несмотря на то, что и традиционный список, и список с переключателями предполагают действие по выбору одного элемента, вам необходимо использовать {@link -android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()}, чтобы сохранить выбор пользователя. Это значит, что при повторном открытии диалогового окна будет отображаться текущий выбор пользователя, а затем создается список с переключателями.

            @@ -442,7 +442,7 @@ android.app.AlertDialog.Builder}.

            одинаковые стили шрифта.

            Для применения макета в вашем {@link android.support.v4.app.DialogFragment} -вам понадобится {@link android.view.LayoutInflater} с +вам понадобится {@link android.view.LayoutInflater} с {@link android.app.Activity#getLayoutInflater()} и вызов {@link android.view.LayoutInflater#inflate inflate()}, где первым параметром будет являться ID ресурса макета, а вторым параметром — исходный вид макета. @@ -470,7 +470,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { public void onClick(DialogInterface dialog, int id) { LoginDialogFragment.this.getDialog().cancel(); } - }); + }); return builder.create(); } @@ -505,7 +505,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {

             public class NoticeDialogFragment extends DialogFragment {
            -    
            +
                 /* The activity that creates an instance of this dialog fragment must
                  * implement this interface in order to receive event callbacks.
                  * Each method passes the DialogFragment in case the host needs to query it. */
            @@ -513,10 +513,10 @@ public class NoticeDialogFragment extends DialogFragment {
                     public void onDialogPositiveClick(DialogFragment dialog);
                     public void onDialogNegativeClick(DialogFragment dialog);
                 }
            -    
            +
                 // Use this instance of the interface to deliver action events
                 NoticeDialogListener mListener;
            -    
            +
                 // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
                 @Override
                 public void onAttach(Activity activity) {
            @@ -543,7 +543,7 @@ public class NoticeDialogFragment extends DialogFragment {
             public class MainActivity extends FragmentActivity
                                       implements NoticeDialogFragment.NoticeDialogListener{
                 ...
            -    
            +
                 public void showNoticeDialog() {
                     // Create an instance of the dialog fragment and show it
                     DialogFragment dialog = new NoticeDialogFragment();
            @@ -638,7 +638,7 @@ android.support.v4.app.Fragment}.

            Тем не менее, в этом случае нельзя использовать{@link android.app.AlertDialog.Builder AlertDialog.Builder} или другие объекты {@link android.app.Dialog} для построения диалогового окна. Если -необходимо сделать {@link android.support.v4.app.DialogFragment} +необходимо сделать {@link android.support.v4.app.DialogFragment} встраиваемым, нужно определить пользовательский интерфейс диалогового окна в макете методом обратного вызова {@link android.support.v4.app.DialogFragment#onCreateView onCreateView()}.

            @@ -656,7 +656,7 @@ public class CustomDialogFragment extends DialogFragment { // Inflate the layout to use as dialog or embedded fragment return inflater.inflate(R.layout.purchase_items, container, false); } - + /** The system calls this only when creating the layout in a dialog. */ @Override public Dialog onCreateDialog(Bundle savedInstanceState) { @@ -678,7 +678,7 @@ public class CustomDialogFragment extends DialogFragment { public void showDialog() { FragmentManager fragmentManager = getSupportFragmentManager(); CustomDialogFragment newFragment = new CustomDialogFragment(); - + if (mIsLargeLayout) { // The device is using a large layout, so show the fragment as a dialog newFragment.show(fragmentManager, "dialog"); @@ -695,12 +695,12 @@ public void showDialog() { }
            -

            Подробные сведения о выполнении операций с фрагментами приведены в руководстве +

            Подробные сведения о выполнении операций с фрагментами приведены в руководстве Фрагменты.

            В приведенном примере mIsLargeLayout булеан указывает, должно ли текущее устройство использовать большой макет приложения (и отображать фрагмент как диалоговое окно, а не -в полноэкранном режиме). Лучшим способом установить такой вид булеана является объявление +в полноэкранном режиме). Лучшим способом установить такой вид булеана является объявление значения булевой переменной с альтернативным значением для других размеров экранов. В качестве примера приведены два варианта булевых ресурсов для различных размеров экранов:

            @@ -776,7 +776,7 @@ android.support.v4.app.DialogFragment#onDismiss onDismiss()} в {@link android.support.v4.app.DialogFragment}.

            Также можно отменить диалоговое окно. Это особое событие, возникающее, когда пользователь -покинул диалоговое окно, не завершив задачу. Так происходит, когда пользователь нажимает кнопку +покинул диалоговое окно, не завершив задачу. Так происходит, когда пользователь нажимает кнопку Назад, касается экрана за областью диалогового окна, либо когда задано {@link android.app.Dialog#cancel()} в {@link android.app.Dialog} (например, в качестве отклика на нажатие кнопки «Отмена» в диалоговом окне).

            diff --git a/docs/html-intl/intl/ru/guide/topics/ui/menus.jd b/docs/html-intl/intl/ru/guide/topics/ui/menus.jd index 2f3ce1eb95804..885918f3e58d3 100644 --- a/docs/html-intl/intl/ru/guide/topics/ui/menus.jd +++ b/docs/html-intl/intl/ru/guide/topics/ui/menus.jd @@ -66,13 +66,13 @@ parent.link=index.html

            Несмотря на то что оформление и поведение некоторых пунктов меню изменились, семантика для определения набора действий и вариантов по-прежнему основана на API-интерфейсах класса {@link android.view.Menu}. В этом -руководстве рассказывается, как создавать три основополагающих типа меню или представлений действий в системе +руководстве рассказывается, как создавать три основополагающих типа меню или представлений действий в системе Android всех версий:

            Меню параметров и строка действий
            Пункты меню параметров представляют собой основные варианты выбора действий в пределах -операции. Именно здесь следует размещать действия, которые затрагивают приложение в целом, например: +операции. Именно здесь следует размещать действия, которые затрагивают приложение в целом, например: "Поиск", "Составить сообщение эл. почты" и "Настройки".

            При разработке приложений для версии Android 2.3 или более ранних версий пользователи могут открыть панель меню параметров нажатием кнопки Меню.

            @@ -83,9 +83,9 @@ Android всех версий:

            строки действий.

            См. раздел Создание меню параметров

            - +
            Контекстное меню и режим контекстных действий
            - +
            Контекстное меню ― это плавающее меню, которое открывается, когда пользователь длительно нажимает на элемент. В нем содержатся действия, которые затрагивают выбранный контент или контекстный кадр. @@ -94,11 +94,11 @@ Android всех версий:

            выбрать сразу несколько элементов.

            См. раздел Создание контекстного меню

            - +
            Всплывающее меню
            Во всплывающем меню отображается вертикальный список пунктов, который привязан к представлению, вызвавшему меню. Он хорошо подходит для предоставления возможности дополнительных вариантов действий, относящихся к определенному контенту или -для выдачи вариантов для второй части команды. Действия во всплывающем меню +для выдачи вариантов для второй части команды. Действия во всплывающем меню не должны напрямую затрагивать соответствующий контент — для этого предназначены контекстные действия. Всплывающее меню предназначено для расширенных действий, относящихся к областям контента в вашей операции. @@ -135,7 +135,7 @@ Android всех версий:

            <item>
            Создает класс {@link android.view.MenuItem}, который представляет один пункт меню. Этот элемент может содержать вложенный элемент <menu> для создания вложенных меню.
            - +
            <group>
            Необязательный, невидимый контейнер для элементов {@code <item>}. Он позволяет разделять пункты меню на категории и назначать им одинаковые свойства, такие как активное состояние и видимость. Подробные @@ -322,7 +322,7 @@ android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} д должен быть общедоступным и принимать один параметр {@link android.view.MenuItem}, — когда система вызывает этот метод, она передает ему выбранный пункт меню. Подробные сведения и пример см. в документе Ресурс меню.

            -

            Совет. Если в приложении предусмотрено несколько операций и +

            Совет. Если в приложении предусмотрено несколько операций и в некоторых из них имеются одинаковые меню параметров, рассмотрите возможность создания операции, которая будет использовать исключительно методы {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} и {@link android.app.Activity#onOptionsItemSelected(MenuItem) @@ -346,7 +346,7 @@ onCreateOptionsMenu()}, она сохранит заполненный вами android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} следует использовать только для создания начального состояния меню, а не для внесения в него изменений в течение жизненного цикла операции.

            -

            Если вам требуется изменять меню параметров в зависимости от +

            Если вам требуется изменять меню параметров в зависимости от событий, которые возникают в течение жизненного цикла операции, сделать это можно в методе{@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}. Этот метод передает объект {@link android.view.Menu} в том виде, в котором он в данный момент существует. Его-то и можно изменить @@ -363,7 +363,7 @@ onPrepareOptionsMenu()} каждый раз, когда пользователь вызвать метод {@link android.app.Activity#invalidateOptionsMenu invalidateOptionsMenu()}, чтобы запросить у системы вызов метода {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}.

            -

            Примечание. +

            Примечание. Никогда не следует изменять пункты меню параметров с учетом класса {@link android.view.View}, действующего в данный момент. В сенсорном режиме (когда пользователь не использует трекбол или кнопки направления движения) фокус не может переводиться на представления, поэтому никогда не следует использовать фокус в качестве основы для изменения @@ -525,7 +525,7 @@ android.widget.ListView} или {@link android.widget.GridView} (что позв представления, то вам следует:

            1. Реализовать интерфейс {@link android.view.ActionMode.Callback}. В его методах обратного вызова вы -можете указать действия для строки контекстных действий, реагировать на нажатия пунктов действий и +можете указать действия для строки контекстных действий, реагировать на нажатия пунктов действий и обрабатывать другие события жизненного цикла для режима действий.
            2. Вызывайте {@link android.app.Activity#startActionMode startActionMode()}, когда требуется показать строку (например, когда пользователь выполняет длительное нажатие представления).
            3. @@ -582,12 +582,12 @@ android.view.ActionMode} можно вносить различные измен android.view.ActionMode#setSubtitle setSubtitle()} (удобно для указания количества выбранных элементов).

              -

              Также обратите внимание, что приведенный выше образец кода задает для переменной {@code mActionMode} значение null, когда +

              Также обратите внимание, что приведенный выше образец кода задает для переменной {@code mActionMode} значение null, когда режим действия прекращает свое существование. Далее вы узнаете, каким образом он инициализируется и чем может быть полезно сохранение составной переменной в операции или фрагменте.

              -
            4. Для включения режима контекстных действий, когда это необходимо, +
            5. Для включения режима контекстных действий, когда это необходимо, например, в ответ на длительное нажатие {@link android.view.View}, вызывайте {@link android.app.Activity#startActionMode startActionMode()}:

              @@ -727,7 +727,7 @@ android.widget.AbsListView.MultiChoiceModeListener#onCreateActionMode onCreateAc

              Если для определения меню используется XML, вот каким образом можно показать всплывающее меню:

                -
              1. Создайте экземпляр класса {@link android.widget.PopupMenu} с помощью его конструктора, принимающий +
              2. Создайте экземпляр класса {@link android.widget.PopupMenu} с помощью его конструктора, принимающий текущие {@link android.content.Context} и {@link android.view.View} приложения, к которым должно быть привязано меню.
              3. С помощью {@link android.view.MenuInflater} загрузите свой ресурс меню в объект {@link @@ -742,8 +742,8 @@ android.widget.PopupMenu#getMenu() PopupMenu.getMenu()}. На API уровня 1
                 <ImageButton
                -    android:layout_width="wrap_content" 
                -    android:layout_height="wrap_content" 
                +    android:layout_width="wrap_content"
                +    android:layout_height="wrap_content"
                     android:src="@drawable/ic_overflow_holo_dark"
                     android:contentDescription="@string/descr_overflow_button"
                     android:onClick="showPopup" />
                @@ -901,7 +901,7 @@ android.view.MenuItem#setChecked(boolean) setChecked()}.

                (например {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}). Именно здесь необходимо задать состояние флажка, поскольку флажок или переключатель не изменяет свое состояние автоматически. Запросить текущее состояние пункта (в котором он находился до того, как был -выбран пользователем) можно с помощью{@link android.view.MenuItem#isChecked()}, а затем задать помеченное состояние с помощью +выбран пользователем) можно с помощью{@link android.view.MenuItem#isChecked()}, а затем задать помеченное состояние с помощью {@link android.view.MenuItem#setChecked(boolean) setChecked()}. Например:

                @@ -1023,9 +1023,9 @@ Intent. Например:

                </intent-filter>
                -

                Подробные сведения о написании фильтров Intent см. в документе +

                Подробные сведения о написании фильтров Intent см. в документе Объекты Intent и фильтры объектов Intent.

                -

                Образец приложения, в котором используется эта методика, см. в образце кода +

                Образец приложения, в котором используется эта методика, см. в образце кода Note Pad.

                diff --git a/docs/html-intl/intl/ru/guide/topics/ui/notifiers/notifications.jd b/docs/html-intl/intl/ru/guide/topics/ui/notifiers/notifications.jd index d072b77eae241..c286431c00fe5 100644 --- a/docs/html-intl/intl/ru/guide/topics/ui/notifiers/notifications.jd +++ b/docs/html-intl/intl/ru/guide/topics/ui/notifiers/notifications.jd @@ -92,7 +92,7 @@ page.title=Уведомления

                Поскольку уведомления являются как важной составной частью пользовательского интерфейса Android, для них имеются собственные инструкции по проектированию. Появившиеся в Android 5.0 (уровень API 21) значительные изменения дизайна имеют особо важное значение, поэтому для получения более подробной информации вам следует ознакомиться с учебником по интерфейсу Material Design -. Чтобы узнать, как проектировать уведомления и взаимодействие с ними, прочитайте руководство по проектированию +. Чтобы узнать, как проектировать уведомления и взаимодействие с ними, прочитайте руководство по проектированию Уведомления.

                Создание уведомления

                @@ -294,7 +294,7 @@ mBuilder.setStyle(inBoxStyle); Обеспечьте доступ к этой функции операции {@link android.app.Activity} всех пользователей, сделав так, чтобы эта операция запускалась, когда пользователь нажимает уведомление. Для этого создайте объект {@link android.app.PendingIntent} - для операции {@link android.app.Activity}. Вызовите + для операции {@link android.app.Activity}. Вызовите {@link android.support.v4.app.NotificationCompat.Builder#setContentIntent setContentIntent()}, чтобы добавить объект {@link android.app.PendingIntent} в уведомление.
              4. @@ -333,7 +333,7 @@ mBuilder.setStyle(inBoxStyle); вызова метода {@link android.app.NotificationManager#notify(int, android.app.Notification) NotificationManager.notify()}. Чтобы изменить это уведомление, после того как оно выдано, обновите или создайте объект {@link android.support.v4.app.NotificationCompat.Builder}, - постройте на его основе объект {@link android.app.Notification} и выдайте + постройте на его основе объект {@link android.app.Notification} и выдайте объект {@link android.app.Notification} с тем же идентификатором, который использовался ранее. Если предыдущее уведомление все еще отображается на экране, система обновит его с использованием содержимого объекта{@link android.app.Notification}. Если предыдущее уведомление было закрыто, то @@ -451,14 +451,14 @@ numMessages = 0; Добавьте поддержку для версии Android 4.0.3 и более ранних версий. Для этого укажите родительский объект операции {@link android.app.Activity}, которую запускаете, добавив элемент <meta-data> - в качестве дочернего для элемента + в качестве дочернего для элемента <activity>.

                Для этого элемента задайте android:name="android.support.PARENT_ACTIVITY". Задайте android:value="<parent_activity_name>", - где <parent_activity_name> ― это значение + где <parent_activity_name> ― это значение android:name для родительского элемента <activity> @@ -466,7 +466,7 @@ numMessages = 0;

              5. - Также добавьте поддержку для версии Android 4.1 и более поздних версий. Для этого добавьте атрибут + Также добавьте поддержку для версии Android 4.1 и более поздних версий. Для этого добавьте атрибут android:parentActivityName в элемент <activity> @@ -513,7 +513,7 @@ numMessages = 0; запускает {@link android.app.Activity}. Этот метод также добавляет флаги, которые запускают стек в новой задаче.

                - Примечание. Несмотря на то что аргумент + Примечание. Несмотря на то что аргумент {@link android.support.v4.app.TaskStackBuilder#addParentStack addParentStack()} является ссылкой на запускаемую операцию {@link android.app.Activity}, при вызове этого метода не добавляется объект {@link android.content.Intent}, который запускает операцию @@ -536,7 +536,7 @@ numMessages = 0; в нее с помощью действия "Назад".

              6. - Получите объект {@link android.app.PendingIntent} для этого стека переходов назад путем вызова метода + Получите объект {@link android.app.PendingIntent} для этого стека переходов назад путем вызова метода {@link android.support.v4.app.TaskStackBuilder#getPendingIntent getPendingIntent()}. Затем этот объект {@link android.app.PendingIntent} можно будет использовать в качестве аргумента для метода {@link android.support.v4.app.NotificationCompat.Builder#setContentIntent @@ -576,7 +576,7 @@ mNotificationManager.notify(id, builder.build()); Особой операции {@link android.app.Activity} не требуется стек перехода назад, поэтому не нужно определять иерархию объектов {@link android.app.Activity} в файле манифеста и вызывать - метод {@link android.support.v4.app.TaskStackBuilder#addParentStack addParentStack()} для построения + метод {@link android.support.v4.app.TaskStackBuilder#addParentStack addParentStack()} для построения стека перехода назад. Вместо этого в файле манифеста задайте параметры задачи {@link android.app.Activity} и создайте объект {@link android.app.PendingIntent} путем вызова метода {@link android.app.PendingIntent#getActivity getActivity()}: @@ -597,7 +597,7 @@ mNotificationManager.notify(id, builder.build()); android:taskAffinity=""
                - В сочетании с + В сочетании с флагом {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_NEW_TASK}, который вы задали в коде, это гарантирует, что данная операция {@link android.app.Activity} не перейдет в задачу приложения, используемую по умолчанию. Любые существующие задачи, имеющие @@ -629,11 +629,11 @@ mNotificationManager.notify(id, builder.build()); Построение и выдача уведомления:
                1. - Создайте объект {@link android.content.Intent}, который запускает операцию + Создайте объект {@link android.content.Intent}, который запускает операцию {@link android.app.Activity}.
                2. - Настройте операцию {@link android.app.Activity}, запускаемую в новой пустой задаче, путем вызова метода + Настройте операцию {@link android.app.Activity}, запускаемую в новой пустой задаче, путем вызова метода {@link android.content.Intent#setFlags setFlags()} с флагами {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_NEW_TASK} и @@ -714,7 +714,7 @@ mNotificationManager.notify(id, builder.build()); {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress(max, progress, false)}, а затем выдайте уведомление. По мере выполнения увеличивайте значение progress и обновляйте уведомление. По окончании операции - progress должен быть равен max. Стандартный способ вызова метода + progress должен быть равен max. Стандартный способ вызова метода {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress()} заключается в следующем: задать значение max равным 100 с последующим увеличением progress в виде величины "процента выполнения" операции. @@ -841,7 +841,7 @@ mNotifyManager.notify(0, mBuilder.build());

                  Примеры ситуаций, в которых могут быть вызваны уведомления heads-up:

                    -
                  • операция пользователя выполняется в полноэкранном режиме (приложение использует +
                  • операция пользователя выполняется в полноэкранном режиме (приложение использует {@link android.app.Notification#fullScreenIntent}) или;
                  • уведомление имеет высокий приоритет и использует рингтоны или вибрацию.
                  • @@ -915,7 +915,7 @@ Notification notification = new Notification.Builder(context)

                    Примечание. Прекращение использования класса {@link android.media.RemoteControlClient} -имеет и другие последствия для управления мультимедиа. Подробные сведения о новых API-интерфейсах для управления сеансами воспроизведения мультимедиа см. в разделе +имеет и другие последствия для управления мультимедиа. Подробные сведения о новых API-интерфейсах для управления сеансами воспроизведения мультимедиа см. в разделе Управление воспроизведением мультимедиа .

                    diff --git a/docs/html-intl/intl/ru/guide/topics/ui/overview.jd b/docs/html-intl/intl/ru/guide/topics/ui/overview.jd index 0e9628b6d0162..8bb953f80d016 100644 --- a/docs/html-intl/intl/ru/guide/topics/ui/overview.jd +++ b/docs/html-intl/intl/ru/guide/topics/ui/overview.jd @@ -39,7 +39,7 @@ XML позволяет создавать удобочитаемую струк
                     <?xml version="1.0" encoding="utf-8"?>
                     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    -              android:layout_width="fill_parent" 
                    +              android:layout_width="fill_parent"
                                   android:layout_height="fill_parent"
                                   android:orientation="vertical" >
                         <TextView android:id="@+id/text"
                    @@ -60,7 +60,7 @@ XML позволяет создавать удобочитаемую струк
                     

                    Полное руководство по созданию макета пользовательского интерфейса см. в документе Макеты XML. - +

                    Компоненты пользовательского интерфейса

                    Не обязательно создавать все элементы пользовательского интерфейса с помощью объектов {@link android.view.View} и {@link diff --git a/docs/html-intl/intl/ru/guide/topics/ui/settings.jd b/docs/html-intl/intl/ru/guide/topics/ui/settings.jd index 4325439721deb..9adfd62305151 100644 --- a/docs/html-intl/intl/ru/guide/topics/ui/settings.jd +++ b/docs/html-intl/intl/ru/guide/topics/ui/settings.jd @@ -82,7 +82,7 @@ API-интерфейсы {@link android.preference.Preference} системы An

                    Рисунок 1. Снимки экранов настроек приложения Android -для обмена сообщениями. Выбор элемента, заданного посредством {@link android.preference.Preference}, +для обмена сообщениями. Выбор элемента, заданного посредством {@link android.preference.Preference}, открывает интерфейс для изменения значения.

                    @@ -143,7 +143,7 @@ android.preference.PreferenceFragment} описана в разделах Каждая настройка для вашего приложения представлена конкретным подклассом класса {@link android.preference.Preference}. Каждый подкласс содержит набор основных свойств, которые позволяют вам указывать, например, заголовок для настройки и ее значение по умолчанию. Каждый подкласс также содержит -собственные специализированные свойства и пользовательский интерфейс. В качестве примера на рисунке 1 показан снимок экрана настроек +собственные специализированные свойства и пользовательский интерфейс. В качестве примера на рисунке 1 показан снимок экрана настроек приложения Android для обмена сообщениями. Каждый элемент списка на экране настроек возвращается отдельным объектом {@link android.preference.Preference}.

                    @@ -226,7 +226,7 @@ android.preference.ListPreference}. Оба содержат следующие
                    {@code android:key}
                    Этот атрибут необходим для предпочтений, которые сохраняют значение данных. Он задает уникальный ключ (строку), который использует система при сохранении значения этой настройки в {@link -android.content.SharedPreferences}. +android.content.SharedPreferences}.

                    Этот атрибут не является обязательным только когда предпочтение представляет собой {@link android.preference.PreferenceCategory} или {@link android.preference.PreferenceScreen}, либо предпочтение указывает намерение {@link android.content.Intent} для вызова (посредством элемента {@code <intent>}) или фрагмент {@link android.app.Fragment} для отображения (с помощью атрибута {@code @@ -271,7 +271,7 @@ android.preference.PreferenceCategory <PreferenceCategory>}.
                    2.

                    Вы можете пользоваться одним или обоими из этих методов группировки для организации настроек в вашем приложении. Принимая -решение об используемом варианте и о разделении настроек на группы, вы должны следовать инструкциям в разделе +решение об используемом варианте и о разделении настроек на группы, вы должны следовать инструкциям в разделе Настройки руководства «Дизайн для Android».

                    @@ -285,7 +285,7 @@ android.preference.PreferenceCategory}.

                     <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
                    -    <PreferenceCategory 
                    +    <PreferenceCategory
                             android:title="@string/pref_sms_storage_title"
                             android:key="pref_key_storage_settings">
                             <CheckBoxPreference
                    @@ -293,12 +293,12 @@ android.preference.PreferenceCategory}.

                    android:summary="@string/pref_summary_auto_delete" android:title="@string/pref_title_auto_delete" android:defaultValue="false"... /> - <Preference + <Preference android:key="pref_key_sms_delete_limit" android:dependency="pref_key_auto_delete" android:summary="@string/pref_summary_delete_limit" android:title="@string/pref_title_sms_delete"... /> - <Preference + <Preference android:key="pref_key_mms_delete_limit" android:dependency="pref_key_auto_delete" android:summary="@string/pref_summary_delete_limit" @@ -430,7 +430,7 @@ public class SettingsActivity extends PreferenceActivity {

                    При разработке приложений для Android 3.0 (API уровня 11) и более поздних версий необходимо использовать {@link android.preference.PreferenceFragment} для отображения списка -объектов {@link android.preference.Preference}. Вы можете добавить {@link android.preference.PreferenceFragment} в любую операцию, при этом +объектов {@link android.preference.Preference}. Вы можете добавить {@link android.preference.PreferenceFragment} в любую операцию, при этом необязательно использовать {@link android.preference.PreferenceActivity}.

                    Фрагменты обеспечивают более @@ -588,11 +588,11 @@ android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()}, чтоб

                     <?xml version="1.0" encoding="utf-8"?>
                     <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
                    -    <header 
                    +    <header
                             android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentOne"
                             android:title="@string/prefs_category_one"
                             android:summary="@string/prefs_summ_category_one" />
                    -    <header 
                    +    <header
                             android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentTwo"
                             android:title="@string/prefs_category_two"
                             android:summary="@string/prefs_summ_category_two" >
                    @@ -636,7 +636,7 @@ public static class SettingsFragment extends PreferenceFragment {
                     

                    Отображение заголовков

                    Чтобы отобразить заголовки предпочтений, вы должны реализовать метод обратного вызова {@link -android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} и вызвать +android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} и вызвать {@link android.preference.PreferenceActivity#loadHeadersFromResource loadHeadersFromResource()}. Например:

                    @@ -672,38 +672,38 @@ android.preference.Preference <Preference>} отправляет наме для загрузки.

                    В качестве примера приведен XML-файл для заголовков предпочтений, который используется в Android версии 3.0 -и более поздних версий ({@code res/xml/preference_headers.xml}):

                    +и более поздних версий ({@code res/xml/preference_headers.xml}):

                     <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
                    -    <header 
                    +    <header
                             android:fragment="com.example.prefs.SettingsFragmentOne"
                             android:title="@string/prefs_category_one"
                             android:summary="@string/prefs_summ_category_one" />
                    -    <header 
                    +    <header
                             android:fragment="com.example.prefs.SettingsFragmentTwo"
                             android:title="@string/prefs_category_two"
                             android:summary="@string/prefs_summ_category_two" />
                     </preference-headers>
                     
                    -

                    А здесь представлен файл предпочтений, который содержит те же самые заголовки для версий старше +

                    А здесь представлен файл предпочтений, который содержит те же самые заголовки для версий старше Android 3.0 ({@code res/xml/preference_headers_legacy.xml}):

                     <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
                    -    <Preference 
                    +    <Preference
                             android:title="@string/prefs_category_one"
                             android:summary="@string/prefs_summ_category_one"  >
                    -        <intent 
                    +        <intent
                                 android:targetPackage="com.example.prefs"
                                 android:targetClass="com.example.prefs.SettingsActivity"
                                 android:action="com.example.prefs.PREFS_ONE" />
                         </Preference>
                    -    <Preference 
                    +    <Preference
                             android:title="@string/prefs_category_two"
                             android:summary="@string/prefs_summ_category_two" >
                    -        <intent 
                    +        <intent
                                 android:targetPackage="com.example.prefs"
                                 android:targetClass="com.example.prefs.SettingsActivity"
                                 android:action="com.example.prefs.PREFS_TWO" />
                    @@ -975,11 +975,11 @@ android.preference.DialogPreference}, в котором объявляется 
                     public class NumberPickerPreference extends DialogPreference {
                         public NumberPickerPreference(Context context, AttributeSet attrs) {
                             super(context, attrs);
                    -        
                    +
                             setDialogLayoutResource(R.layout.numberpicker_dialog);
                             setPositiveButtonText(android.R.string.ok);
                             setNegativeButtonText(android.R.string.cancel);
                    -        
                    +
                             setDialogIcon(null);
                         }
                         ...
                    @@ -992,7 +992,7 @@ public class NumberPickerPreference extends DialogPreference {
                     
                     

                    Вы можете сохранить значение настройки в любой момент, вызвав один из методов {@code persist*()} класса {@link android.preference.Preference}, например, {@link -android.preference.Preference#persistInt persistInt()}, если настройка имеет целое значение, или +android.preference.Preference#persistInt persistInt()}, если настройка имеет целое значение, или {@link android.preference.Preference#persistBoolean persistBoolean()} для сохранения логического значения.

                    Примечание. Каждое предпочтение {@link android.preference.Preference} может сохранять только один @@ -1071,7 +1071,7 @@ android.preference.Preference#getPersistedInt getPersistedInt()} не может

                    Предоставление значения по умолчанию

                    -

                    Если экземпляр вашего класса {@link android.preference.Preference} указывает значение по умолчанию +

                    Если экземпляр вашего класса {@link android.preference.Preference} указывает значение по умолчанию (с помощью атрибута {@code android:defaultValue}), система вызывает {@link android.preference.Preference#onGetDefaultValue onGetDefaultValue()}, когда она создает экземпляр объекта для извлечения значения. Вы должны реализовать @@ -1194,7 +1194,7 @@ protected void onRestoreInstanceState(Parcelable state) { // Cast state to custom BaseSavedState and pass to superclass SavedState myState = (SavedState) state; super.onRestoreInstanceState(myState.getSuperState()); - + // Set this Preference's widget to reflect the restored state mNumberPicker.setValue(myState.value); } diff --git a/docs/html-intl/intl/ru/guide/topics/ui/ui-events.jd b/docs/html-intl/intl/ru/guide/topics/ui/ui-events.jd index cd2b4813cf834..9f3609bea789b 100644 --- a/docs/html-intl/intl/ru/guide/topics/ui/ui-events.jd +++ b/docs/html-intl/intl/ru/guide/topics/ui/ui-events.jd @@ -30,7 +30,7 @@ parent.link=index.html которые называются приемниками событий, и служат перехватчиками действий пользователя с вашим пользовательским интерфейсом.

                    Несмотря на то, что вы будете чаще использовать приемники событий для перехвата действий пользователя, может -наступить момент, когда вам не захочется наследовать класс View, чтобы создать нестандартный компонент. +наступить момент, когда вам не захочется наследовать класс View, чтобы создать нестандартный компонент. Возможно, вы захотите наследовать класс {@link android.widget.Button}, чтобы сделать нечто более необычное. В этом случае вы сможете определить поведение события по умолчанию для своего класса с помощью обработчиков событий класса.

                    @@ -46,27 +46,27 @@ parent.link=index.html
                    onClick()
                    -
                    Из объекта {@link android.view.View.OnClickListener}. +
                    Из объекта {@link android.view.View.OnClickListener}. Этот метод вызывается, когда пользователь касается элемента (в режиме касания), или переводит фокус на элемент с помощью клавиш перемещения или трекбола и нажимает соответствующую клавишу «ввода» или нажимает на трекбол.
                    onLongClick()
                    -
                    Из объекта {@link android.view.View.OnLongClickListener}. +
                    Из объекта {@link android.view.View.OnLongClickListener}. Этот метод вызывается, когда пользователь касается элемента и удерживает его (в режиме касания), или переводит фокус на элемент с помощью клавиш перемещения или трекбола и нажимает и удерживает соответствующую клавишу «ввода» или трекбол (в течение одной секунды).
                    onFocusChange()
                    -
                    Из объекта {@link android.view.View.OnFocusChangeListener}. +
                    Из объекта {@link android.view.View.OnFocusChangeListener}. Этот метод вызывается, когда пользователь перемещается в элемент или из него с помощью клавиш перемещения или трекбола.
                    onKey()
                    -
                    Из объекта {@link android.view.View.OnKeyListener}. +
                    Из объекта {@link android.view.View.OnKeyListener}. Этот метод вызывается, когда пользователь переносит фокус на элемент и нажимает или отпускает аппаратную клавишу на устройстве.
                    onTouch()
                    -
                    Из объекта {@link android.view.View.OnTouchListener}. +
                    Из объекта {@link android.view.View.OnTouchListener}. Этот метод вызывается, когда пользователь выполняет действие, считающееся событием касания, например, нажимает, отпускает или выполняет любой жест на экране (в пределах границ элемента).
                    onCreateContextMenu()
                    -
                    Из объекта {@link android.view.View.OnCreateContextMenuListener}. +
                    Из объекта {@link android.view.View.OnCreateContextMenuListener}. Этот метод вызывается, когда создается контекстное меню (в результате длительного «длительного нажатия»). См. обсуждение контекстных меню в руководстве для разработчиков Меню.
                    @@ -75,8 +75,8 @@ parent.link=index.html

                    Эти методы являются единственными составными частями соответствующих интерфейсов. Чтобы определить один из этих методов и обрабатывать события, реализуйте вложенный интерфейс в вашем процесс или определите его, как анонимный класс. Затем передайте экземпляр реализации -в соответствующий метод View.set...Listener(). (Например, вызовите -{@link android.view.View#setOnClickListener(View.OnClickListener) setOnClickListener()} +в соответствующий метод View.set...Listener(). (Например, вызовите +{@link android.view.View#setOnClickListener(View.OnClickListener) setOnClickListener()} и передайте ему свою реализацию {@link android.view.View.OnClickListener OnClickListener}.)

                    В следующем примере показано, как зарегистрировать приемник события «по клику» (on-click) для кнопки.

                    @@ -122,7 +122,7 @@ public class ExampleActivity extends Activity implements OnClickListener { зависит от события. Для некоторых методов, которые возвращают значения, причина описана ниже:

                    • {@link android.view.View.OnLongClickListener#onLongClick(View) onLongClick()} — -этот метод возвращает логическое значение, указывающее, что вы обработали это событие и его более не следует хранить. +этот метод возвращает логическое значение, указывающее, что вы обработали это событие и его более не следует хранить. А именно, верните значение true, чтобы указать, что вы обработали событие и его следует остановить; верните значение false, если вы не обработали его и/или событие должно продолжаться для любых других приемников события on-click.
                    • @@ -181,14 +181,14 @@ dispatchKeyEvent()}. В качестве альтернативы к пе макета, учитывайте и другие методы:

                      • {@link android.app.Activity#dispatchTouchEvent(MotionEvent) - Activity.dispatchTouchEvent(MotionEvent)} — этот метод позволяет вашей операции {@link + Activity.dispatchTouchEvent(MotionEvent)} — этот метод позволяет вашей операции {@link android.app.Activity} перехватывать все события касаний перед их отправкой в окно.
                      • {@link android.view.ViewGroup#onInterceptTouchEvent(MotionEvent) ViewGroup.onInterceptTouchEvent(MotionEvent)} — этот метод позволяет объекту {@link android.view.ViewGroup} просматривать события перед их отправкой в дочерние отображаемые объекты.
                      • {@link android.view.ViewParent#requestDisallowInterceptTouchEvent(boolean) ViewParent.requestDisallowInterceptTouchEvent(boolean)} — вызовите этот метод -в родительском отображаемом объекте, чтобы указать ему, что он не должен перехватывать события касания с помощью {@link +в родительском отображаемом объекте, чтобы указать ему, что он не должен перехватывать события касания с помощью {@link android.view.ViewGroup#onInterceptTouchEvent(MotionEvent)}.
                      @@ -199,7 +199,7 @@ dispatchKeyEvent()}. В качестве альтернативы к пе какой элемент будет принимать ввод. Однако, если устройство поддерживает сенсорный ввод, и пользователь начинает взаимодействовать с интерфейсом, прикасаясь к его элементам, исчезает необходимость выделять элементы или передавать фокус определенному отображаемому объекту. Следовательно, существует режим -взаимодействия, который называется «режимом касания». +взаимодействия, который называется «режимом касания».

                      Как только пользователь касается экрана, устройство, поддерживающее сенсорный ввод, @@ -214,7 +214,7 @@ dispatchKeyEvent()}. В качестве альтернативы к пе с пользовательским интерфейсом без касания экрана.

                      -Состояние режима касания поддерживается во всей системе (для всех окон и операций). +Состояние режима касания поддерживается во всей системе (для всех окон и операций). Чтобы узнать текущее состояние, можно вызвать {@link android.view.View#isInTouchMode} и посмотреть, находится ли устройство в режиме касания.

                      @@ -282,7 +282,7 @@ dispatchKeyEvent()}. В качестве альтернативы к пе the framework will take care of measuring, laying out, and drawing the tree as appropriate.
                - +

                Note: The entire View tree is single threaded. You must always be on the UI thread when calling any method on any View. If you are doing work on other threads and want to update the state of a View diff --git a/docs/html-intl/intl/ru/preview/api-overview.jd b/docs/html-intl/intl/ru/preview/api-overview.jd index d4e60427a98a7..887ea630e79c7 100644 --- a/docs/html-intl/intl/ru/preview/api-overview.jd +++ b/docs/html-intl/intl/ru/preview/api-overview.jd @@ -456,7 +456,7 @@ API-интерфейс платформы, который позволяет п

                Android for Work

                В Android for Work добавлены много новых возможностей и API-интерфейсов для устройств под управлением Android N. -Некоторые из них приведены ниже. Полный список обновлений Android for Work, касающихся +Некоторые из них приведены ниже. Полный список обновлений Android for Work, касающихся Android N, содержится в списке изменений Android for Work.

                Пароль безопасности для рабочего профиля

                diff --git a/docs/html-intl/intl/ru/preview/features/direct-boot.jd b/docs/html-intl/intl/ru/preview/features/direct-boot.jd index b49624bf9216d..3392c1355f8fa 100644 --- a/docs/html-intl/intl/ru/preview/features/direct-boot.jd +++ b/docs/html-intl/intl/ru/preview/features/direct-boot.jd @@ -103,7 +103,7 @@ FileInputStream inStream = directBootContext.openFileInput(appDataFilename);

                Шифрованное хранилище устройства следует использовать только для информации, которая должна быть доступна в режиме Direct Boot. Шифрованное хранилище устройства не следует использовать в качестве шифрованного хранилища общего назначения. -Для хранения данных пользователя или шифрованных данных, которые не требуются в режиме +Для хранения данных пользователя или шифрованных данных, которые не требуются в режиме Direct Boot, следует использовать шифрованное хранилище, требующее ввода учетных данных.

                Уведомление о разблокировке пользователем

                @@ -148,7 +148,7 @@ ACTION_BOOT_COMPLETED}, которое теперь указывает, что Direct Boot на поддерживаемых устройствах с Android N, выполните одну из следующих последовательностей действий.

                  -
                • Включите на устройстве параметры разработчика Developer options, если вы еще не сделали этого ранее. Для этого +
                • Включите на устройстве параметры разработчика Developer options, если вы еще не сделали этого ранее. Для этого перейдите на экран Settings > About phone и нажмите семь раз Build number. Когда параметры разработчика станут доступны, откройте раздел Settings > Developer options и выберите diff --git a/docs/html-intl/intl/ru/preview/features/multi-window.jd b/docs/html-intl/intl/ru/preview/features/multi-window.jd index f1a8ea603ddd0..b45766c169a18 100644 --- a/docs/html-intl/intl/ru/preview/features/multi-window.jd +++ b/docs/html-intl/intl/ru/preview/features/multi-window.jd @@ -356,7 +356,7 @@ android:supportsPictureInPicture=["true" | "false"]

                  Чтобы перевести операцию в режим "картинка в картинке", вызовите новый метод Activity.enterPictureInPicture(). Этот метод игнорируется, если - устройство не поддерживает режим "картинка в картинке". Дополнительная информация содержится в документации + устройство не поддерживает режим "картинка в картинке". Дополнительная информация содержится в документации Режим "картинка в картинке".

                  diff --git a/docs/html-intl/intl/ru/preview/features/multilingual-support.jd b/docs/html-intl/intl/ru/preview/features/multilingual-support.jd index 83dd2b4d15452..83e9968f73da4 100644 --- a/docs/html-intl/intl/ru/preview/features/multilingual-support.jd +++ b/docs/html-intl/intl/ru/preview/features/multilingual-support.jd @@ -208,7 +208,7 @@ it_IT
                  конечных пользователей. Поэтому при разработке приложений для Android N следует использовать средства форматирования, а не жесткое кодирование строк с числами и датами.

                  -

                  В качестве наглядного примера можно привести арабский язык, поддержка которого в Android N расширена +

                  В качестве наглядного примера можно привести арабский язык, поддержка которого в Android N расширена с одного {@code ar_EG} до 27 языковых стандартов. Большинство ресурсов этих языковых стандартов общие, но в некоторых из них используются цифры формата ASCII, а в других — собственные цифры. Например, если вы хотите создать предложение с числовой переменной diff --git a/docs/html-intl/intl/ru/preview/features/notification-updates.jd b/docs/html-intl/intl/ru/preview/features/notification-updates.jd index 9c7cb9347719b..54b3bc36f5d46 100644 --- a/docs/html-intl/intl/ru/preview/features/notification-updates.jd +++ b/docs/html-intl/intl/ru/preview/features/notification-updates.jd @@ -203,7 +203,7 @@ Builder.setGroup()}.

                  -

                  Добавление уведомлений в группу описано в разделе +

                  Добавление уведомлений в группу описано в разделе Добавление каждого уведомления в группу.

                  diff --git a/docs/html-intl/intl/ru/preview/features/scoped-folder-access.jd b/docs/html-intl/intl/ru/preview/features/scoped-folder-access.jd index a39230c252fe4..51a4c4d55f791 100644 --- a/docs/html-intl/intl/ru/preview/features/scoped-folder-access.jd +++ b/docs/html-intl/intl/ru/preview/features/scoped-folder-access.jd @@ -113,7 +113,7 @@ startActivityForResult(intent, request_code);

                  Советы и рекомендации

                  По возможности оставляйте постоянный URI для доступа к внешнему каталогу, чтобы приложению не -приходилось многократно запрашивать у пользователя разрешение на доступ. После предоставления доступа пользователем вызовите метод +приходилось многократно запрашивать у пользователя разрешение на доступ. После предоставления доступа пользователем вызовите метод getContentResolver().takePersistableUriPermssion() для URI доступа к каталогу. Система сохранит постоянный URI и при последующих запросах доступа будет возвращать ответ RESULT_OK. Таким образом, приложение не будет постоянно выводить diff --git a/docs/html-intl/intl/ru/preview/features/security-config.jd b/docs/html-intl/intl/ru/preview/features/security-config.jd index de117d68a83e4..5294a4f6bbbdb 100644 --- a/docs/html-intl/intl/ru/preview/features/security-config.jd +++ b/docs/html-intl/intl/ru/preview/features/security-config.jd @@ -133,7 +133,7 @@ page.image=images/cards/card-nyc_2x.jpg

                  - Добавьте самозаверенный сертификат или сертификат закрытого ЦС в формате PEM или DER в + Добавьте самозаверенный сертификат или сертификат закрытого ЦС в формате PEM или DER в {@code res/raw/my_ca}.

                  @@ -209,7 +209,7 @@ page.image=images/cards/card-nyc_2x.jpg При отладке приложения, которое использует для подключения протокол HTTPS, вам может потребоваться подключение к локальному серверу разработки, у которого нет сертификата SSL для рабочего сервера. Чтобы выполнить отладку без изменения кода - приложения, вы можете указать ЦС для отладки, + приложения, вы можете указать ЦС для отладки, которые входят в число доверенных, только если для параметра android:debuggable установлено значение {@code true} с использованием {@code debug-overrides}. Обычно среды разработки и инструменты diff --git a/docs/html-intl/intl/ru/training/basics/activity-lifecycle/index.jd b/docs/html-intl/intl/ru/training/basics/activity-lifecycle/index.jd index b8de11ecea67f..29f1730998e08 100644 --- a/docs/html-intl/intl/ru/training/basics/activity-lifecycle/index.jd +++ b/docs/html-intl/intl/ru/training/basics/activity-lifecycle/index.jd @@ -34,12 +34,12 @@ startpage=true -

                  Во время навигации пользователя по вашему приложению экземпляры +

                  Во время навигации пользователя по вашему приложению экземпляры {@link android.app.Activity} внутри приложения переключаются между разными состояниями их жизненного цикла Например, при первом запуске операции она получает высокий приоритет в системе и привлекает внимание пользователя. Во время этого процесса система Android вызывает серию методов жизненного цикла -операции, позволяя настроить пользовательский интерфейс и другие компоненты. Если пользователь выполняет +операции, позволяя настроить пользовательский интерфейс и другие компоненты. Если пользователь выполняет действие, запускающее другую операцию, или переключается на другое приложение, система вызывает другой набор методов жизненного цикла для операции, поскольку она переносится на фоновый уровень (операция больше не отображается, но экземпляр и состояние остаются без изменений).

                  @@ -50,12 +50,12 @@ startpage=true а сетевое соединение разрывалось. После возврата пользователя проигрыватель может снова подключиться к сети, и пользователь сможет возобновить воспроизведение видео с того же самого места.

                  -

                  В этом учебном курсе разъясняются важные методы обратного вызова жизненного цикла, которые получает каждый экземпляр {@link +

                  В этом учебном курсе разъясняются важные методы обратного вызова жизненного цикла, которые получает каждый экземпляр {@link android.app.Activity}, и описывается как их использовать, чтобы операция выполнялась так, как этого ожидает пользователь, и не потребляла системные ресурсы, когда они ей не нужны.

                  Уроки

                  - +
                  Запуск операции
                  Из этого урока вы узнаете об основах жизненного цикла операций, способах запуска вашего приложения пользователями и вариантах @@ -68,5 +68,5 @@ android.app.Activity}, и описывается как их использов
                  Повторное создание операции
                  Вы узнаете, что происходит при полном прекращении операции, и как можно восстановить ее состояние в случае необходимости.
                  -
                  +
            diff --git a/docs/html-intl/intl/ru/training/basics/activity-lifecycle/pausing.jd b/docs/html-intl/intl/ru/training/basics/activity-lifecycle/pausing.jd index c4837809acf22..8d1ce92655117 100644 --- a/docs/html-intl/intl/ru/training/basics/activity-lifecycle/pausing.jd +++ b/docs/html-intl/intl/ru/training/basics/activity-lifecycle/pausing.jd @@ -8,13 +8,13 @@ trainingnavtop=true
            - +

            Содержание этого урока

            1. Приостановка операции
            2. Возобновление операции
            - +

            См. также:

            -
            - + +

            Если вы хотите изменить частоту фоновых обновлений, чтобы продлить время работы устройства от батареи, сначала рекомендуется проверить текущий уровень заряда и состояние зарядки.

            Именно от этих двух факторов зависит, как обновления повлияют на время работы устройства от батареи. Когда устройство подключено к сети переменного тока, приложение можно обновлять максимально часто, поскольку процесс обновления не будет сказываться на уровне заряда батареи. Если устройство не подключено к сети, следует воздержаться от обновлений, чтобы продлить время его работы от батареи.

            @@ -34,8 +34,8 @@ next.link=docking-monitoring.html

            Если заряд батареи практически исчерпан, можно снизить частоту обновлений (вплоть до их полного прекращения).

            -

            Определение текущего состояния зарядки

            - +

            Определение текущего состояния зарядки

            +

            Начните с определения текущего состояния зарядки. {@link android.os.BatteryManager} передает все сведения о батарее и зарядке в закрепленном намерении {@link android.content.Intent}, которое содержит также информацию о состоянии зарядки.

            Поскольку это намерение является закрепленным, регистрировать {@link android.content.BroadcastReceiver} не нужно. Чтобы получить текущее состояние батареи в виде намерения, нужно вызвать {@code registerReceiver}, передав {@code null} в качестве приемника, как показано в коде ниже. Можно также передать фактический объект {@link android.content.BroadcastReceiver}, но это необязательно, поскольку обработка обновлений будет выполняться позднее.

            @@ -58,7 +58,7 @@ boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;

            Как правило, если устройство подключено к сети переменного тока, фоновые обновления можно выполнять с максимальной частотой. Если устройство заряжается через USB, частоту можно несколько сократить, а если устройство не подключено к сети – сократить еще больше.

            -

            Отслеживание изменений состояния зарядки

            +

            Отслеживание изменений состояния зарядки

            Состояние зарядки изменяется всякий раз, когда пользователь подключает устройство к источнику питания. Поскольку это случается довольно часто, важно отслеживать изменения этого состояния и соответствующим образом корректировать частоту обновления приложения.

            @@ -75,11 +75,11 @@ boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
            public class PowerConnectionReceiver extends BroadcastReceiver {
                 @Override
            -    public void onReceive(Context context, Intent intent) { 
            +    public void onReceive(Context context, Intent intent) {
                     int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                     boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                                         status == BatteryManager.BATTERY_STATUS_FULL;
            -    
            +
                     int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                     boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
                     boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
            @@ -87,7 +87,7 @@ boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
            } -

            Определение текущего уровня заряда батареи

            +

            Определение текущего уровня заряда батареи

            В некоторых случаях целесообразно определять текущий уровень заряда батареи. Если он ниже определенного значения, частоту фоновых обновлений следует уменьшить.

            @@ -99,7 +99,7 @@ int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1); float batteryPct = level / (float)scale; -

            Отслеживание существенных изменений уровня заряда батареи

            +

            Отслеживание существенных изменений уровня заряда батареи

            Отслеживать состояние батареи непрерывно не следует,

            diff --git a/docs/html-intl/intl/ru/training/monitoring-device-state/connectivity-monitoring.jd b/docs/html-intl/intl/ru/training/monitoring-device-state/connectivity-monitoring.jd index ca1a9423692f8..d37243193e9ec 100644 --- a/docs/html-intl/intl/ru/training/monitoring-device-state/connectivity-monitoring.jd +++ b/docs/html-intl/intl/ru/training/monitoring-device-state/connectivity-monitoring.jd @@ -11,7 +11,7 @@ next.link=manifest-receivers.html @jd:body -
            +

            Содержание урока

            @@ -27,7 +27,7 @@ next.link=manifest-receivers.html
          • Намерения и фильтры намерений
          - +

          Чаще всего повторяющиеся оповещения и фоновые службы используются для планового обновления приложения из Интернета, кэширования или загрузки больших объемов данных. Однако если подключение к Интернету не установлено или скорость соединения слишком низкая, выполнять загрузку не имеет смысла.

          @@ -35,18 +35,18 @@ next.link=manifest-receivers.html

          Проверить наличие подключения к Интернету и его тип можно с помощью {@link android.net.ConnectivityManager}.

          -

          Определение наличия подключения к Интернету

          - +

          Определение наличия подключения к Интернету

          +

          Если подключение отсутствует, нет смысла планировать обновление из Интернета. В приведенном ниже коде показано, как использовать {@link android.net.ConnectivityManager} для отправки запросов об активной сети и определять возможности подключения.

          ConnectivityManager cm =
                   (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
          - 
          +
           NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
           boolean isConnected = activeNetwork.isConnectedOrConnecting();
          -

          Определение типа подключения к Интернету

          +

          Определение типа подключения к Интернету

          Также можно определить тип доступного в настоящий момент подключения к Интернету.

          @@ -59,7 +59,7 @@ boolean isConnected = activeNetwork.isConnectedOrConnecting();

          Когда обновления отключены, необходимо отслеживать изменения доступных соединений, чтобы возобновить их сразу после подключения устройства к Интернету.

          -

          Отслеживание изменения возможностей подключения

          +

          Отслеживание изменения возможностей подключения

          {@link android.net.ConnectivityManager} передает действие {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION} ({@code "android.net.conn.CONNECTIVITY_CHANGE"}) при каждом изменении сведений о подключении. Зарегистрируйте в манифесте приемник широковещательных намерений, чтобы отслеживать эти изменения и запускать (или приостанавливать) фоновые обновления соответствующим образом.

          diff --git a/docs/html-intl/intl/ru/training/monitoring-device-state/docking-monitoring.jd b/docs/html-intl/intl/ru/training/monitoring-device-state/docking-monitoring.jd index d94f3570458cc..002f35155a22b 100644 --- a/docs/html-intl/intl/ru/training/monitoring-device-state/docking-monitoring.jd +++ b/docs/html-intl/intl/ru/training/monitoring-device-state/docking-monitoring.jd @@ -10,7 +10,7 @@ next.link=connectivity-monitoring.html @jd:body -
          +

          Содержание урока

          @@ -26,7 +26,7 @@ next.link=connectivity-monitoring.html
        • Намерения и фильтры намерений
        - +

        Устройства под управлением ОС Android можно подключать к нескольким типам док-станций: настольным, которые делятся на цифровые и аналоговые, и автомобильным. В большинстве случаев устройства заряжаются при подключении к док-станции, поэтому состояние подключения к док-станции часто связано с состоянием зарядки.

        @@ -36,8 +36,8 @@ next.link=connectivity-monitoring.html

        Состояние подключения к док-станции также передается в виде закрепленного намерения {@link android.content.Intent}, что позволяет запрашивать сведения о наличии подключения к док-станции и ее типе.

        -

        Определение текущего состояния подключения к док-станции

        - +

        Определение текущего состояния подключения к док-станции

        +

        Сведения о состоянии подключения к док-станции передаются в качестве дополнительных данных в закрепленном оповещении действия {@link android.content.Intent#ACTION_DOCK_EVENT}. Поскольку это закрепленное намерение, регистрировать {@link android.content.BroadcastReceiver} не требуется. Достаточно вызвать {@link android.content.Context#registerReceiver registerReceiver()}, передав {@code null} в качестве приемника широковещательных намерений, как показано в коде ниже.

        IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT);
        @@ -49,9 +49,9 @@ Intent dockStatus = context.registerReceiver(null, ifilter);
        boolean isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED; -

        Определение типа док-станции

        +

        Определение типа док-станции

        -

        Док-станция, к которой подключено устройство, может быть одного из четырех типов: +

        Док-станция, к которой подключено устройство, может быть одного из четырех типов:

        • автомобильная;
        • настольная;
        • настольная с минимальным набором функций (аналоговая);
        • @@ -60,12 +60,12 @@ boolean isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;

          Обратите внимание, что последние два типа поддерживаются только на уровне API 11, поэтому, даже если вас не интересует, является ли док-станция цифровой или аналоговой, а интересует только ее тип, рекомендуется выполнять проверку по всем трем типам:

          boolean isCar = dockState == EXTRA_DOCK_STATE_CAR;
          -boolean isDesk = dockState == EXTRA_DOCK_STATE_DESK || 
          +boolean isDesk = dockState == EXTRA_DOCK_STATE_DESK ||
                            dockState == EXTRA_DOCK_STATE_LE_DESK ||
                            dockState == EXTRA_DOCK_STATE_HE_DESK;
          -

          Отслеживание изменений состояния подключения к док-станции и ее типа

          +

          Отслеживание изменений состояния подключения к док-станции и ее типа

          При каждом подключении устройства к док-станции или отключении от нее передается действие {@link android.content.Intent#ACTION_DOCK_EVENT}. Чтобы отслеживать состояние подключения к док-станции, достаточно зарегистрировать в манифесте приложения приемник широковещательных намерений, как показано ниже.

          diff --git a/docs/html-intl/intl/ru/training/monitoring-device-state/index.jd b/docs/html-intl/intl/ru/training/monitoring-device-state/index.jd index c87d9af5da4da..e26af09a9c2b6 100644 --- a/docs/html-intl/intl/ru/training/monitoring-device-state/index.jd +++ b/docs/html-intl/intl/ru/training/monitoring-device-state/index.jd @@ -7,10 +7,10 @@ next.link=battery-monitoring.html @jd:body -
          +
          -

          Требования

          +

          Требования

          -
          +

          Качественное приложение должно оказывать минимальное влияние на время работы устройства от батареи. В этом уроке вы научитесь создавать приложения, способные изменять функционал и режим работы в зависимости от состояния устройства.

          Отключение обновления данных фоновых служб при потере подключения и снижение частоты обновления при низком заряде батареи позволяет снизить расход энергии и продлить работу устройства без подзарядки.

          -

          Уроки

          - +

          Уроки

          + - +will want to jump to a lesson or not.--> +
          Отслеживание уровня заряда батареи и состояния зарядки
          Вы узнаете, как изменять частоту обновления приложения, определяя и отслеживая текущий уровень заряда батареи и изменение состояния зарядки.
          @@ -46,4 +46,4 @@ will want to jump to a lesson or not.-->
          Операции с приемниками широковещательных намерений по запросу
          Приемники широковещательных намерений, объявленные в манифесте, можно включать и отключать во время работы приложения. Это позволяет отключать ненужные приемники в зависимости от состояния устройства. Вы узнаете, как повысить эффективность путем включения, отключения или каскадирования приемников изменения состояния и как отложить действие до момента перехода устройства в заданное состояние.
          -
          \ No newline at end of file + \ No newline at end of file diff --git a/docs/html-intl/intl/ru/training/monitoring-device-state/manifest-receivers.jd b/docs/html-intl/intl/ru/training/monitoring-device-state/manifest-receivers.jd index 724ee93e28223..2bd0fb93658e7 100644 --- a/docs/html-intl/intl/ru/training/monitoring-device-state/manifest-receivers.jd +++ b/docs/html-intl/intl/ru/training/monitoring-device-state/manifest-receivers.jd @@ -9,7 +9,7 @@ previous.link=connectivity-monitoring.html @jd:body -
          +

          Содержание урока

          @@ -23,7 +23,7 @@ previous.link=connectivity-monitoring.html
        • Намерения и фильтры намерений
        - +

        Самый простой способ отслеживать изменения состояния устройства – создать приемники {@link android.content.BroadcastReceiver} для каждого отслеживаемого состояния и зарегистрировать их в манифесте приложения. Затем в каждом из этих приемников можно переопределять график повторяющихся оповещений в зависимости от текущего состояния устройства.

        @@ -31,10 +31,10 @@ previous.link=connectivity-monitoring.html

        Этот способ имеет недостатки: приложение активирует устройство при каждом запуске любого из этих приемников, что далеко не всегда оправданно.

        Оптимальный вариант – включать и выключать приемники широковещательных намерений во время работы приложения. Это позволяет использовать приемники, объявленные в манифесте, как пассивные оповещения, которые инициируются системными событиями только в случае необходимости.

        - -

        Включение, отключение и каскадирование приемников изменения состояния для повышения эффективности

        - + +

        Включение, отключение и каскадирование приемников изменения состояния для повышения эффективности

        +

        {@link android.content.pm.PackageManager} позволяет включать и выключать любые компоненты, определенные в манифесте, в том числе все приемники широковещательных намерений:

        ComponentName receiver = new ComponentName(context, myReceiver.class);
        diff --git a/docs/html-intl/intl/ru/training/multiscreen/adaptui.jd b/docs/html-intl/intl/ru/training/multiscreen/adaptui.jd
        index 490a64ad2de6a..ee1dd9dcd1672 100644
        --- a/docs/html-intl/intl/ru/training/multiscreen/adaptui.jd
        +++ b/docs/html-intl/intl/ru/training/multiscreen/adaptui.jd
        @@ -10,9 +10,9 @@ previous.link=screendensities.html
         
         
         
        -
        -
        - +
        +
        +

        Содержание урока

          @@ -27,17 +27,17 @@ previous.link=screendensities.html - +

          Упражнение

          - + - - -
        -
        +

        NewsReader.zip

        +
        + + +
        +

        Алгоритм пользовательского интерфейса зависит от макета, который в данный момент отображается. Например, если приложение работает в двухпанельном режиме, то при нажатии на элемент в левой панели содержание отобразится в правой. В однопанельном режиме содержание откроется отдельно (в другой активности).

        @@ -56,7 +56,7 @@ public class NewsReaderActivity extends FragmentActivity { setContentView(R.layout.main_layout); View articleView = findViewById(R.id.article); - mIsDualPane = articleView != null && + mIsDualPane = articleView != null && articleView.getVisibility() == View.VISIBLE; } } @@ -116,7 +116,7 @@ public void onCreate(Bundle savedInstanceState) { else { /* use list navigation (spinner) */ actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST); - SpinnerAdapter adap = new ArrayAdapter(this, + SpinnerAdapter adap = new ArrayAdapter(this, R.layout.headline_item, CATEGORIES); actionBar.setListNavigationCallbacks(adap, handler); } @@ -168,7 +168,7 @@ public class HeadlinesFragment extends ListFragment { public class HeadlinesFragment extends ListFragment { ... @Override - public void onItemClick(AdapterView<?> parent, + public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (null != mHeadlineSelectedListener) { mHeadlineSelectedListener.onHeadlineSelected(position); diff --git a/docs/html-intl/intl/ru/training/multiscreen/index.jd b/docs/html-intl/intl/ru/training/multiscreen/index.jd index 84b9b8b5bdf06..66cf968edf9b9 100644 --- a/docs/html-intl/intl/ru/training/multiscreen/index.jd +++ b/docs/html-intl/intl/ru/training/multiscreen/index.jd @@ -7,10 +7,10 @@ next.link=screensizes.html @jd:body -
        -
        - -

        Требования

        +
        +
        + +

        Требования

        - +

        NewsReader.zip

        +
        + +
        +
        +

        На платформе Android работают устройства с самыми разными размерами экрана: от телефонов до телевизоров. Чтобы с вашим приложением могли работать как можно больше пользователей, оно должно корректно отображаться на всех этих устройствах.

        Однако совместимость с разными типами устройств – это еще не все. От размера экрана зависит, какие возможности будет иметь пользователь при работе с приложением. Чтобы пользователи действительно остались довольны вашим приложением, оно должно не просто поддерживать разные экраны, но и быть оптимизировано для каждого из них.

        @@ -48,17 +48,17 @@ href="{@docRoot}tools/support-library/index.html">вспомогательной

        Примечание. В этом модуле и в учебном приложении используется вспомогательная библиотека, позволяющая работать с API {@link android.app.Fragment} в версиях до Android 3.0. Чтобы иметь возможность использовать все необходимые API, загрузите библиотеку и добавьте ее в свое приложение.

        - -

        Уроки

        - -
        -
        Поддержка разных размеров экрана
        -
        В этом уроке рассказывается, как создать макет, который адаптируется к разным размерам экрана, используя масштабируемые представления, объекты {@link android.widget.RelativeLayout}, квалификаторы размера и ориентации, фильтры псевдонимов и растровые изображений формата nine-patch.
        - -
        Поддержка разных разрешений экрана
        -
        В этом уроке рассказывается, как работать с экранами разного разрешения с помощью не зависящих от разрешения пикселей и как подготовить растровые изображения для каждого из них.
        - -
        Реализация адаптируемых алгоритмов работы пользовательского интерфейса
        -
        В этом уроке рассказывается, как реализовать алгоритм работы интерфейса, адаптирующийся к размеру и разрешению экрана, то есть способный определять активный макет во время выполнения приложения, выбирать дальнейшие действия на основе текущего макета и обрабатывать изменения конфигурации экрана.
        -
        + +

        Уроки

        + +
        +
        Поддержка разных размеров экрана
        +
        В этом уроке рассказывается, как создать макет, который адаптируется к разным размерам экрана, используя масштабируемые представления, объекты {@link android.widget.RelativeLayout}, квалификаторы размера и ориентации, фильтры псевдонимов и растровые изображений формата nine-patch.
        + +
        Поддержка разных разрешений экрана
        +
        В этом уроке рассказывается, как работать с экранами разного разрешения с помощью не зависящих от разрешения пикселей и как подготовить растровые изображения для каждого из них.
        + +
        Реализация адаптируемых алгоритмов работы пользовательского интерфейса
        +
        В этом уроке рассказывается, как реализовать алгоритм работы интерфейса, адаптирующийся к размеру и разрешению экрана, то есть способный определять активный макет во время выполнения приложения, выбирать дальнейшие действия на основе текущего макета и обрабатывать изменения конфигурации экрана.
        +
        diff --git a/docs/html-intl/intl/ru/training/multiscreen/screendensities.jd b/docs/html-intl/intl/ru/training/multiscreen/screendensities.jd index cfd4724628240..ffcdbbca23274 100644 --- a/docs/html-intl/intl/ru/training/multiscreen/screendensities.jd +++ b/docs/html-intl/intl/ru/training/multiscreen/screendensities.jd @@ -12,8 +12,8 @@ next.link=adaptui.html -
        -
        +
        +

        Содержание урока

          @@ -29,15 +29,15 @@ next.link=adaptui.html

      Упражнение

      - - - +

      NewsReader.zip

      + + + + +

      В этом уроке рассказывается, как создать интерфейс, поддерживающий разные разрешения экрана, за счет использования разных ресурсов и не зависящих от разрешения единиц измерения.

      @@ -48,8 +48,8 @@ next.link=adaptui.html

      Например, если вы задаете расстояние между двумя представлениями, рекомендуется использовать dp, а не px:

      -<Button android:layout_width="wrap_content" 
      -    android:layout_height="wrap_content" 
      +<Button android:layout_width="wrap_content"
      +    android:layout_height="wrap_content"
           android:text="@string/clickme"
           android:layout_marginTop="20dp" />
       
      @@ -57,8 +57,8 @@ next.link=adaptui.html

      Для определения размера шрифта всегда используйте sp:

      -<TextView android:layout_width="match_parent" 
      -    android:layout_height="wrap_content" 
      +<TextView android:layout_width="match_parent"
      +    android:layout_height="wrap_content"
           android:textSize="20sp" />
       
      diff --git a/docs/html-intl/intl/ru/training/multiscreen/screensizes.jd b/docs/html-intl/intl/ru/training/multiscreen/screensizes.jd index 9684d77486dde..57496d9b18bf1 100644 --- a/docs/html-intl/intl/ru/training/multiscreen/screensizes.jd +++ b/docs/html-intl/intl/ru/training/multiscreen/screensizes.jd @@ -10,8 +10,8 @@ next.link=screendensities.html -
      -
      +
      +

      Содержание урока

        @@ -30,26 +30,26 @@ next.link=screendensities.html
      1. Поддержка нескольких экранов
    -

    Упражнение

    - -
    +

    Упражнение

    + + - -
    - +

    NewsReader.zip

    + + + +

    В этом уроке описаны следующие аспекты обеспечения совместимости интерфейса с разными экранами:

    -
      -
    • обеспечение способности макета адаптироваться к размеру экрана;
    • -
    • выбор макета интерфейса, отвечающего конфигурации экрана;
    • +
        +
      • обеспечение способности макета адаптироваться к размеру экрана;
      • +
      • выбор макета интерфейса, отвечающего конфигурации экрана;
      • контроль правильности применяемого макета;
      • -
      • использование масштабируемых растровых изображений.
      • -
      +
    • использование масштабируемых растровых изображений.
    • +
    -

    Использование параметров wrap_content и match_parent

    +

    Использование параметров wrap_content и match_parent

    Чтобы создать масштабируемый макет, способный адаптироваться к разным экранам, используйте в качестве значений ширины и высоты отдельных компонентов представления параметры "wrap_content" и "match_parent". Если используется "wrap_content", для ширины или высоты представления устанавливается минимальное значение, позволяющее уместить содержание на экран, а параметр "match_parent" (известный как "fill_parent" в API до 8 уровня) служит для растягивания компонента по размеру родительского представления.

    @@ -65,7 +65,7 @@ next.link=screendensities.html

    Рисунок 1. Приложение News Reader при вертикальной (слева) и горизонтальной (справа) ориентации.

    -

    Использование объекта RelativeLayout

    +

    Использование объекта RelativeLayout

    С помощью вложенных экземпляров объекта {@link android.widget.LinearLayout} и параметров "wrap_content" и "match_parent" можно создавать достаточно сложные макеты. Однако {@link android.widget.LinearLayout} не дает возможности точно управлять взаимным расположением дочерних представлений: в {@link android.widget.LinearLayout} они просто помещаются в ряд друг за другом. Если необходимо расположить дочерние представления иным образом, используйте объект {@link android.widget.RelativeLayout}, позволяющий задать относительные позиции компонентов. Например, одно дочернее представление можно выровнять по левому краю экрана, а другое – по правому.

    @@ -115,8 +115,8 @@ next.link=screendensities.html

    Обратите внимание: несмотря на изменение размера компонентов их взаимное расположение остается прежним, так как оно задано объектом {@link android.widget.RelativeLayout.LayoutParams}.

    - -

    Использование квалификаторов размера

    + +

    Использование квалификаторов размера

    Масштабируемые или относительные макеты, один из которых продемонстрирован выше, имеют свои ограничения. Хотя они позволяют создать интерфейс, способный адаптироваться к разным экранам за счет растягивания пространства внутри и вокруг компонентов, пользователю может оказаться не слишком удобно работать с таким интерфейсом. Поэтому в приложении должен использоваться не один масштабируемый макет, а несколько альтернативных вариантов для разных конфигураций экрана. Их можно создать с помощью квалификаторов конфигураций, которые позволяют оперативно выбирать ресурсы, отвечающие текущим параметрам экрана (например, разные варианты макетов для экранов разных размеров).

    @@ -158,7 +158,7 @@ next.link=screendensities.html

    Следует учесть, что на Android-устройствах до версии 3.2 квалификатор sw600dp не будет работать, поэтому для них по-прежнему нужно использовать large. Таким образом, вам потребуется еще один файл с названием res/layout-large/main.xml, идентичный файлу res/layout-sw600dp/main.xml. В следующем разделе вы познакомитесь с методом, который позволяет избежать дублирования таких файлов макета.

    -

    Использование псевдонимов макетов

    +

    Использование псевдонимов макетов

    Квалификатор Smallest-width работает только на устройствах Android 3.2 или более поздних версий. Для совместимости с более ранними устройствами по-прежнему следует использовать абстрактные размеры (small, normal, large и xlarge). Например, чтобы интерфейс открывался в однопанельном режиме на телефонах и в многопанельном на планшетных ПК с 7-дюймовым экраном, телевизорах и других крупных устройствах, подготовьте следующие файлы:

    @@ -202,7 +202,7 @@ next.link=screendensities.html {@code large}, а для более новых – sw600dp).

    -

    Использование квалификаторов ориентации

    +

    Использование квалификаторов ориентации

    Хотя некоторые макеты одинаково хорошо смотрятся в вертикальной и горизонтальной ориентациях, в большинстве случаев интерфейс все же приходится адаптировать. Ниже показано, как изменяется макет в приложении News Reader в зависимости от размера и ориентации экрана.

    diff --git a/docs/html-intl/intl/vi/design/patterns/navigation.jd b/docs/html-intl/intl/vi/design/patterns/navigation.jd index 98490db0e5b63..a3d6003dd4169 100644 --- a/docs/html-intl/intl/vi/design/patterns/navigation.jd +++ b/docs/html-intl/intl/vi/design/patterns/navigation.jd @@ -168,7 +168,7 @@ cần chụp ảnh có thể kích hoạt ứng dụng Camera, ứng dụng này thông tin và tất cả hành động liên kết mà người dùng có thể thực hiện. Ứng dụng của bạn là tập hợp của nhiều hoạt động, bao gồm cả hoạt động do bạn tạo và hoạt động mà bạn sử dụng lại từ các ứng dụng khác.

    -

    Tác vụ là trình tự các hoạt động mà một người dùng tuân theo để hoàn thành một mục tiêu. +

    Tác vụ là trình tự các hoạt động mà một người dùng tuân theo để hoàn thành một mục tiêu. Tác vụ đơn có thể sử dụng các hoạt động từ chỉ một ứng dụng, hoặc có thể dựa trên hoạt động từ nhiều ứng dụng khác nhau.

    diff --git a/docs/html-intl/intl/vi/guide/components/activities.jd b/docs/html-intl/intl/vi/guide/components/activities.jd index 83e7669a7f767..304b73c879952 100644 --- a/docs/html-intl/intl/vi/guide/components/activities.jd +++ b/docs/html-intl/intl/vi/guide/components/activities.jd @@ -57,7 +57,7 @@ hoạt động có thể bắt đầu một hoạt động khác để thực hi mới bắt đầu, hoạt động trước đó sẽ bị dừng lại, nhưng hệ thống vẫn giữ nguyên hoạt động trong một ngăn xếp ("back stack"). Khi một hoạt động mới bắt đầu, nó được đẩy lên ngăn xếp và chiếm lấy tiêu điểm của người dùng. Ngăn xếp sẽ tuân theo cơ chế xếp chồng cơ bản "vào cuối, ra đầu", -vì thế, khi người dùng kết thúc hoạt động hiện tại và nhấn nút Quay lại, nó +vì thế, khi người dùng kết thúc hoạt động hiện tại và nhấn nút Quay lại, nó sẽ được đẩy ra khỏi ngăn xếp (và bị hủy) và hoạt động trước đó sẽ tiếp tục. (Ngăn xếp được đề cập kỹ hơn trong tài liệu Tác vụ và Ngăn Xếp.)

    @@ -139,7 +139,7 @@ setContentView()}.

    Khai báo hoạt động trong bản kê khai

    Bạn phải khai báo hoạt động của mình trong tệp bản kê khai để hoạt động -có thể truy cập được vào hệ thống. Để khai báo hoạt động của mình, hãy mở tệp bản kê khai của bạn và thêm một phần tử {@code <activity>} +có thể truy cập được vào hệ thống. Để khai báo hoạt động của mình, hãy mở tệp bản kê khai của bạn và thêm một phần tử {@code <activity>} làm con của phần tử {@code <application>} . Ví dụ:

    @@ -161,7 +161,7 @@ bạn phát hành ứng dụng của mình, bạn không nên thay đổi tên n một số tính năng, chẳng hạn như các lối tắt của ứng dụng (hãy đọc bài đăng trên blog, Những Điều Không Thay Đổi Được).

    -

    Xem tài liệu tham khảo phần tử {@code <activity>} +

    Xem tài liệu tham khảo phần tử {@code <activity>} để biết thêm thông tin về việc khai báo hoạt động của bạn trong bản kê khai.

    @@ -200,7 +200,7 @@ tự mình bắt đầu chúng bằng cách sử dụng các ý định rõ ràn

    Tuy nhiên, nếu bạn muốn hoạt động của mình phản hồi lại những ý định ngầm mà được chuyển giao từ các ứng dụng khác (và chính bạn), thì bạn phải định nghĩa các bộ lọc ý định bổ sung cho hoạt động của mình. Với mỗi loại ý định mà bạn muốn phản hồi, bạn phải nêu một {@code -<intent-filter>} bao gồm một phần tử +<intent-filter>} bao gồm một phần tử {@code <action>} và, không bắt buộc, một phần tử {@code <category>} và/hoặc một phần tử {@code @@ -324,7 +324,7 @@ finish()} của nó. Bạn cũng có thể tắt một hoạt động riêng mà bằng cách sử dụng những phương pháp này. Như đề cập trong phần sau về vòng đời của hoạt động, hệ thống Android quản lý tuổi thọ của một hoạt động cho bạn, vì vậy bạn không cần kết thúc các hoạt động của chính mình. Việc gọi những phương pháp này có thể ảnh hưởng tiêu cực tới trải nghiệm người dùng -kỳ vọng và chỉ nên được sử dụng khi bạn tuyệt đối không muốn người dùng quay lại thực thể này của +kỳ vọng và chỉ nên được sử dụng khi bạn tuyệt đối không muốn người dùng quay lại thực thể này của hoạt động.

    @@ -350,7 +350,7 @@ che toàn bộ màn hình. Trạng thái tạm dừng hoàn toàn đang hoạt trình quản lý cửa sổ), nhưng có thể bị hệ thống tắt bỏ trong trường hợp bộ nhớ cực kỳ thấp.
    Dừng
    -
    Hoạt động bị che khuất hoàn toàn bởi một hoạt động khác (hoạt động hiện đang +
    Hoạt động bị che khuất hoàn toàn bởi một hoạt động khác (hoạt động hiện đang “dưới nền"). Hoạt động dừng cũng vẫn đang hoạt động ({@link android.app.Activity} đối tượng được giữ lại trong bộ nhớ, nó duy trì tất cả thông tin về trạng thái và thành viên, nhưng không gắn với trình quản lý cửa sổ). Tuy nhiên, hoạt động không còn hiển thị với người dùng nữa và hệ thống @@ -608,7 +608,7 @@ android.app.Activity#onSaveInstanceState onSaveInstanceState()}.

    Hệ thống gọi {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} trước khi khiến hoạt động dễ bị hủy. Hệ thống chuyển cho phương pháp này -một {@link android.os.Bundle} trong đó bạn có thể lưu +một {@link android.os.Bundle} trong đó bạn có thể lưu thông tin trạng thái về hoạt động như cặp tên giá trị, bằng cách sử dụng các phương pháp như {@link android.os.Bundle#putString putString()} và {@link android.os.Bundle#putInt putInt()}. Sau đó, nếu hệ thống tắt bỏ tiến trình ứng dụng của bạn diff --git a/docs/html-intl/intl/vi/guide/components/bound-services.jd b/docs/html-intl/intl/vi/guide/components/bound-services.jd index 7a2ddbaf6321e..9d19e05513eea 100644 --- a/docs/html-intl/intl/vi/guide/components/bound-services.jd +++ b/docs/html-intl/intl/vi/guide/components/bound-services.jd @@ -357,7 +357,7 @@ handleMessage()}.

    Theo cách này, không có "phương pháp" nào để máy khách gọi đối với dịch vụ. Thay vào đó, máy khách -gửi “thông báo” (đối tượng {@link android.os.Message}) mà dịch vụ nhận được trong +gửi “thông báo” (đối tượng {@link android.os.Message}) mà dịch vụ nhận được trong {@link android.os.Handler} của mình.

    Sau đây là một dịch vụ ví dụ đơn giản sử dụng một giao diện {@link android.os.Messenger}:

    @@ -539,7 +539,7 @@ kỹ hơn ở bên dưới.)

    Ví dụ, đoạn mã HTML sau sẽ kết nối máy khách với dịch vụ được tạo bên trên bằng cách -mở rộng lớp Trình gắn kết, vì vậy tất cả những việc mà nó phải làm là đổi kiểu +mở rộng lớp Trình gắn kết, vì vậy tất cả những việc mà nó phải làm là đổi kiểu {@link android.os.IBinder} được trả về thành lớp {@code LocalService} và yêu cầu thực thể {@code LocalService}:

    diff --git a/docs/html-intl/intl/vi/guide/components/fragments.jd b/docs/html-intl/intl/vi/guide/components/fragments.jd index 95d9c76337fc8..7b6346c4d6fda 100644 --- a/docs/html-intl/intl/vi/guide/components/fragments.jd +++ b/docs/html-intl/intl/vi/guide/components/fragments.jd @@ -36,7 +36,7 @@ parent.link=activities.html
  • {@link android.app.FragmentManager}
  • {@link android.app.FragmentTransaction}
  • - +

    Xem thêm

    1. Xây dựng một UI Động bằng các Phân đoạn
    2. @@ -148,7 +148,7 @@ của bạn.

      khởi tạo các thành phần thiết yếu của phân đoạn mà bạn muốn giữ lại khi phân đoạn bị tạm dừng hoặc dừng hẳn, sau đó tiếp tục.
    {@link android.app.Fragment#onCreateView onCreateView()}
    -
    Hệ thống sẽ gọi phương pháp này khi đến lúc phân đoạn vẽ giao diện người dùng của nó +
    Hệ thống sẽ gọi phương pháp này khi đến lúc phân đoạn vẽ giao diện người dùng của nó lần đầu tiên. Để vẽ một UI cho phân đoạn của mình, bạn phải trả về một {@link android.view.View} từ phương pháp này, đây là gốc của bố trí phân đoạn của bạn. Bạn có thể trả về giá trị rỗng nếu phân đoạn không cung cấp UI.
    @@ -303,7 +303,7 @@ phân đoạn:

    • Cung cấp thuộc tính {@code android:id} với một ID duy nhất.
    • Cung cấp thuộc tính {@code android:tag} với một xâu duy nhất.
    • -
    • Nếu bạn không cung cấp được thuộc tính nào, hệ thống sẽ sử dụng ID của dạng xem +
    • Nếu bạn không cung cấp được thuộc tính nào, hệ thống sẽ sử dụng ID của dạng xem của bộ chứa.
    @@ -362,7 +362,7 @@ findFragmentByTag()}.

    Để biết ví dụ về hoạt động sử dụng phân đoạn như một trình thực hiện nền, không có UI, hãy xem mẫu {@code FragmentRetainInstance.java}, mẫu này có trong các mẫu SDK (có sẵn thông qua -Trình quản lý SDK Android) và nằm trên hệ thống của bạn như là +Trình quản lý SDK Android) và nằm trên hệ thống của bạn như là <sdk_root>/APIDemos/app/src/main/java/com/example/android/apis/app/FragmentRetainInstance.java.

    @@ -378,7 +378,7 @@ có nó, hãy gọi {@link android.app.Activity#getFragmentManager()} từ hoạ
  • Nhận các phân đoạn tồn tại trong hoạt động, bằng {@link android.app.FragmentManager#findFragmentById findFragmentById()} (đối với các phân đoạn cung cấp UI trong bố trí hoạt động) hoặc {@link android.app.FragmentManager#findFragmentByTag -findFragmentByTag()} (đối với các phân đoạn có hoặc không cung cấp UI).
  • +findFragmentByTag()} (đối với các phân đoạn có hoặc không cung cấp UI).
  • Lấy phân đoạn ra khỏi ngăn xếp, bằng {@link android.app.FragmentManager#popBackStack()} (mô phỏng một câu lệnh Quay lại của người dùng).
  • Đăng ký một đối tượng theo dõi cho những thay đổi đối với ngăn xếp, bằng {@link @@ -562,9 +562,9 @@ public static class FragmentA extends ListFragment { } -

    Nếu hoạt động chưa triển khai giao diện, khi đó phân đoạn sẽ đưa ra lỗi +

    Nếu hoạt động chưa triển khai giao diện, khi đó phân đoạn sẽ đưa ra lỗi {@link java.lang.ClassCastException}. -Nếu thành công, thành viên {@code mListener} giữ một tham chiếu tới triển khai +Nếu thành công, thành viên {@code mListener} giữ một tham chiếu tới triển khai {@code OnArticleSelectedListener}của hoạt động, sao cho phân đoạn A có thể chia sẻ sự kiện với hoạt động bằng cách gọi các phương pháp được định nghĩa bởi giao diện {@code OnArticleSelectedListener}. Ví dụ, nếu phân đoạn A là một phần mở rộng của {@link android.app.ListFragment}, mỗi lần @@ -785,7 +785,7 @@ android.widget.FrameLayout}), hoặc bắt đầu một hoạt động mới (t

    Phân đoạn thứ hai, {@code DetailsFragment} sẽ hiển thị tóm tắt vở kịch cho mục được chọn từ danh sách trong {@code TitlesFragment}:

    - + {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details}

    Nhớ lại ở lớp {@code TitlesFragment} rằng, nếu người dùng nhấp vào một mục danh sách và bố trí @@ -798,7 +798,7 @@ tóm tắt vở kịch được chọn khi màn hình ở hướng đứng:

    {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details_activity} - +

    Lưu ý rằng hoạt động này tự kết thúc nếu cấu hình là khổ ngang, sao cho hoạt động chính có thể chiếm lấy và hiển thị {@code DetailsFragment} bên cạnh {@code TitlesFragment}. Điều này có thể xảy ra nếu người dùng bắt đầu {@code DetailsActivity} ở dạng hướng đứng, nhưng diff --git a/docs/html-intl/intl/vi/guide/components/fundamentals.jd b/docs/html-intl/intl/vi/guide/components/fundamentals.jd index 4b70140723d95..725c68dacb686 100644 --- a/docs/html-intl/intl/vi/guide/components/fundamentals.jd +++ b/docs/html-intl/intl/vi/guide/components/fundamentals.jd @@ -295,16 +295,16 @@ android.app.Activity} và các thuộc tính {@code android:label} quy định m

    Bạn phải khai báo tất cả thành phần của ứng dụng như sau:

    • Các phần tử <activity> +href="{@docRoot}guide/topics/manifest/activity-element.html"><activity> cho hoạt động
    • Các phần tử <service> cho dịch vụ
    • Các phần tử <receiver> +href="{@docRoot}guide/topics/manifest/receiver-element.html"><receiver> cho hàm nhận quảng bá
    • Các phần tử <provider> +href="{@docRoot}guide/topics/manifest/provider-element.html"><provider> cho trình cung cấp nội dung
    @@ -379,7 +379,7 @@ chúng, nhưng các dịch vụ bên ngoài như Google Play thì có đọc đ cho người dùng khi họ tìm kiếm ứng dụng từ thiết bị của mình.

    Ví dụ, nếu ứng dụng của bạn yêu cầu máy ảnh và sử dụng các API được giới thiệu trong Android 2.1 (API Mức 7), -bạn cần khai báo những điều này như yêu cầu trong tệp bản kê khai của mình như sau:

    +bạn cần khai báo những điều này như yêu cầu trong tệp bản kê khai của mình như sau:

     <manifest ... >
    diff --git a/docs/html-intl/intl/vi/guide/components/index.jd b/docs/html-intl/intl/vi/guide/components/index.jd
    index 966597d999c20..87b51c2849b02 100644
    --- a/docs/html-intl/intl/vi/guide/components/index.jd
    +++ b/docs/html-intl/intl/vi/guide/components/index.jd
    @@ -1,7 +1,7 @@
     page.title=Thành phần Ứng dụng
     page.landing=true
    -page.landing.intro=Khuôn khổ ứng dụng của Android cho phép bạn tạo lập nhiều ứng dụng đa dạng và sáng tạo bằng cách sử dụng một tập hợp các thành phần có thể tái sử dụng. Phần này giải thích cách bạn có thể xây dựng các thành phần định nghĩa các khối dựng cho ứng dụng của mình và cách kết nối chúng với nhau bằng cách sử dụng ý định. 
    -page.metaDescription=Khuôn khổ ứng dụng của Android cho phép bạn tạo lập nhiều ứng dụng đa dạng và sáng tạo bằng cách sử dụng một tập hợp các thành phần có thể tái sử dụng. Phần này giải thích cách bạn có thể xây dựng các thành phần định nghĩa các khối dựng cho ứng dụng của mình và cách kết nối chúng với nhau bằng cách sử dụng ý định. 
    +page.landing.intro=Khuôn khổ ứng dụng của Android cho phép bạn tạo lập nhiều ứng dụng đa dạng và sáng tạo bằng cách sử dụng một tập hợp các thành phần có thể tái sử dụng. Phần này giải thích cách bạn có thể xây dựng các thành phần định nghĩa các khối dựng cho ứng dụng của mình và cách kết nối chúng với nhau bằng cách sử dụng ý định.
    +page.metaDescription=Khuôn khổ ứng dụng của Android cho phép bạn tạo lập nhiều ứng dụng đa dạng và sáng tạo bằng cách sử dụng một tập hợp các thành phần có thể tái sử dụng. Phần này giải thích cách bạn có thể xây dựng các thành phần định nghĩa các khối dựng cho ứng dụng của mình và cách kết nối chúng với nhau bằng cách sử dụng ý định.
     page.landing.image=images/develop/app_components.png
     page.image=images/develop/app_components.png
     
    @@ -11,7 +11,7 @@ page.image=images/develop/app_components.png
     
       

    Bài viết Blog

    - +

    Sử dụng DialogFragments

    Trong bài viết này, tôi sẽ trình bày cách sử dụng DialogFragments bằng thư viện hỗ trợ v4 (cho khả năng tương thích ngược trên các thiết bị chạy phiên bản trước Honeycomb) để hiển thị một hộp thoại chỉnh sửa đơn giản và trả về một kết quả cho lệnh gọi Hoạt động bằng cách sử dụng một giao diện.

    @@ -21,7 +21,7 @@ page.image=images/develop/app_components.png

    Phân đoạn cho Tất cả

    Hôm nay, chúng tôi đã phát hành một thư viện tĩnh giới thiệu API Phân đoạn (cũng như LoaderManager mới và một vài lớp khác) tương tự sao cho các ứng dụng tương thích với phiên bản Android 1.6 hoặc mới hơn có thể sử dụng phân đoạn để tạo các giao diện người dùng tương thích với máy tính bảng.

    - +

    Tạo đa luồng cho Hiệu năng

    Một cách làm hay trong khi tạo các ứng dụng hồi đáp đó là đảm bảo luồng UI chính của bạn @@ -32,7 +32,7 @@ xử lý trong một luồng khác.

  • - +

    Lớp khóa

    1. {@link android.app.LoaderManager}
    2. {@link android.content.Loader}
    3. -
    - + +

    Các mẫu liên quan

    1. @@ -51,7 +51,7 @@ thay đổi.
    2. tạo lại sau khi cấu hình thay đổi. Vì thế, chúng không cần truy vấn lại dữ liệu của mình. - +

      Tổng quan về API Trình tải

      Có nhiều lớp và giao diện có thể có liên quan trong khi sử dụng @@ -129,10 +129,10 @@ của {@link android.content.Loader} hoặc {@link android.content.AsyncTaskLoad dữ liệu từ một số nguồn khác.

    3. Một triển khai cho {@link android.app.LoaderManager.LoaderCallbacks}. Đây là nơi bạn tạo trình tải mới và quản lý các tham chiếu của mình tới các -trình tải hiện có.
    4. +trình tải hiện có.
    5. Một cách để hiển thị dữ liệu của trình tải, chẳng hạn như {@link android.widget.SimpleCursorAdapter}.
    6. -
    7. Một nguồn dữ liệu, chẳng hạn như một {@link android.content.ContentProvider}, khi sử dụng một +
    8. Một nguồn dữ liệu, chẳng hạn như một {@link android.content.ContentProvider}, khi sử dụng một {@link android.content.CursorLoader}.
    9. Khởi động một Trình tải

      @@ -140,7 +140,7 @@ android.widget.SimpleCursorAdapter}.

      {@link android.app.LoaderManager} quản lý một hoặc nhiều thực thể {@link android.content.Loader} trong một {@link android.app.Activity} hoặc {@link android.app.Fragment}. Chỉ có một {@link -android.app.LoaderManager} trên mỗi hoạt động hoặc phân đoạn.

      +android.app.LoaderManager} trên mỗi hoạt động hoặc phân đoạn.

      Thông thường, bạn sẽ khởi tạo một {@link android.content.Loader} bên trong phương pháp {@link @@ -157,13 +157,13 @@ tham số sau:

      • Một ID duy nhất xác định trình tải. Trong ví dụ này, ID là 0.
      • Các tham đối tùy chọn để cung cấp cho trình tải khi -xây dựng (null trong ví dụ này).
      • +xây dựng (null trong ví dụ này). -
      • Triển khai {@link android.app.LoaderManager.LoaderCallbacks}, phương pháp mà +
      • Triển khai {@link android.app.LoaderManager.LoaderCallbacks}, phương pháp mà {@link android.app.LoaderManager} gọi để báo cáo các sự kiện trình tải. Trong ví dụ này , lớp cục bộ triển khai giao diện {@link android.app.LoaderManager.LoaderCallbacks}, vì thế nó chuyển một tham chiếu -tới chính nó, {@code this}.
      • +tới chính nó, {@code this}.

      Lệnh gọi {@link android.app.LoaderManager#initLoader initLoader()} đảm bảo rằng một trình tải được khởi tạo và hiện hoạt. Nó có hai kết quả có thể xảy ra:

      @@ -193,7 +193,7 @@ vòng đời của trình tải. {@link android.app.LoaderManager} khởi động và dừng tải khi cần và duy trì trạng thái của trình tải và nội dung đi kèm của nó. Như hàm ý, bạn hiếm khi tương tác trực tiếp với các trình tải (thông qua một ví dụ về việc sử dụng các phương pháp trình tải để tinh chỉnh hành vi -của một trình tải, hãy xem ví dụ
      LoaderThrottle). +của một trình tải, hãy xem ví dụ LoaderThrottle). Bạn thường sử dụng nhất là các phương pháp {@link android.app.LoaderManager.LoaderCallbacks} để can thiệp vào tiến trình tải khi diễn ra một sự kiện đặc biệt. Để thảo luận thêm về chủ đề này, hãy xem phần Sử dụng Phương pháp Gọi lại LoaderManager.

      @@ -245,7 +245,7 @@ Khởi tạo và trả về một {@link android.content.Loader} mới cho ID đ — Được gọi khi một trình tải được tạo trước đó đã hoàn tất việc tải.
        -
      • {@link android.app.LoaderManager.LoaderCallbacks#onLoaderReset onLoaderReset()} +
      • {@link android.app.LoaderManager.LoaderCallbacks#onLoaderReset onLoaderReset()} — Được gọi khi một trình tải được tạo trước đó đang được đặt lại, vì thế mà khiến dữ liệu của nó không sẵn có.
      • @@ -315,7 +315,7 @@ public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        Phương pháp này được gọi khi một trình tải được tạo trước đó đã hoàn thành việc tải của mình. Phương pháp này được bảo đảm sẽ được gọi trước khi giải phóng dữ liệu cuối cùng được cung cấp cho trình tải này. Tại điểm này, bạn nên loại bỏ mọi trường hợp sử dụng -dữ liệu cũ (do nó sẽ được giải phóng sớm), nhưng không nên +dữ liệu cũ (do nó sẽ được giải phóng sớm), nhưng không nên tự mình giải phóng dữ liệu do trình tải sở hữu dữ liệu và sẽ đảm nhận việc này.

        @@ -340,11 +340,11 @@ public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

        onLoaderReset

        -

        Phương pháp này được gọi khi một trình tải được tạo trước đó đang được đặt lại, vì thế mà khiến +

        Phương pháp này được gọi khi một trình tải được tạo trước đó đang được đặt lại, vì thế mà khiến dữ liệu của nó không sẵn có. Lệnh gọi lại này cho phép bạn tìm hiểu xem khi nào thì dữ liệu sẽ được giải phóng để bạn có thể loại bỏ tham chiếu của mình tới nó.  

        -

        Sự triển khai này gọi ra -{@link android.widget.SimpleCursorAdapter#swapCursor swapCursor()} +

        Sự triển khai này gọi ra +{@link android.widget.SimpleCursorAdapter#swapCursor swapCursor()} với một giá trị null:

        @@ -366,7 +366,7 @@ public void onLoaderReset(Loader<Cursor> loader) {
         android.app.Fragment} có chức năng hiển thị một {@link android.widget.ListView} chứa
         kết quả của một truy vấn đối với trình cung cấp nội dung danh bạ. Nó sử dụng một {@link
         android.content.CursorLoader} để quản lý truy vấn trên trình cung cấp.

        - +

        Để một ứng dụng truy cập danh bạ của một người dùng, như minh họa trong ví dụ này, bản kê khai của nó phải bao gồm quyền {@link android.Manifest.permission#READ_CONTACTS READ_CONTACTS}.

        diff --git a/docs/html-intl/intl/vi/guide/components/processes-and-threads.jd b/docs/html-intl/intl/vi/guide/components/processes-and-threads.jd index 390ca156a1f05..b9933edc07fe9 100644 --- a/docs/html-intl/intl/vi/guide/components/processes-and-threads.jd +++ b/docs/html-intl/intl/vi/guide/components/processes-and-threads.jd @@ -120,7 +120,7 @@ bắt buộc để đảm bảo giao diện người dùng có phản hồi.

        • Nó lưu trữ một {@link android.app.Activity} mà không nằm trong tiền cảnh, nhưng vẫn -hiển thị với người dùng (phương pháp {@link android.app.Activity#onPause onPause()} của nó đã được gọi). +hiển thị với người dùng (phương pháp {@link android.app.Activity#onPause onPause()} của nó đã được gọi). Điều này có thể xảy ra, ví dụ, nếu hoạt động tiền cảnh đã bắt đầu một hộp thoại, nó cho phép hoạt động trước được nhìn thấy phía sau nó.
        • @@ -202,7 +202,7 @@ gọi lại của hệ thống (chẳng hạn như {@link android.view.View#onKe hoặc một phương pháp gọi lại vòng đời) sẽ luôn chạy trong luồng UI của tiến trình.

          Ví dụ, khi người dùng chạm vào một nút trên màn hình, luồng UI của ứng dụng của bạn sẽ phân phối -sự kiện chạm tới widget, đến lượt mình, widget sẽ đặt trạng thái được nhấn và đăng một yêu cầu vô hiệu hóa tới +sự kiện chạm tới widget, đến lượt mình, widget sẽ đặt trạng thái được nhấn và đăng một yêu cầu vô hiệu hóa tới hàng đợi sự kiện. Luồng UI loại yêu cầu khỏi hàng đợi và thông báo với widget rằng nó nên tự vẽ lại .

          @@ -319,7 +319,7 @@ private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } - + /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { diff --git a/docs/html-intl/intl/vi/guide/components/recents.jd b/docs/html-intl/intl/vi/guide/components/recents.jd index 0a176145f9caa..271c05d9142e9 100644 --- a/docs/html-intl/intl/vi/guide/components/recents.jd +++ b/docs/html-intl/intl/vi/guide/components/recents.jd @@ -180,7 +180,7 @@ sau khi người dùng mở một tài liệu bằng ứng dụng:

          bất kỳ hoạt động nào mà người dùng đã gọi ra cuối cùng. -

          Lưu ý: Đối với những giá trị ngoài {@code none} và {@code never} +

          Lưu ý: Đối với những giá trị ngoài {@code none} và {@code never} hoạt động phải được định nghĩa bằng {@code launchMode="standard"}. Nếu thuộc tính này không được quy định thì {@code documentLaunchMode="none"} sẽ được sử dụng.

          @@ -191,7 +191,7 @@ hoàn thành. Bạn có thể khống chế hành vi này bằng lớp {@link an bằng một cờ {@link android.content.Intent}, hoặc bằng một thuộc tính <activity>.

          -

          Bạn có thể luôn loại trừ hoàn toàn một tác vụ khỏi màn hình tổng quan bằng cách thiết đặt thuộc tính +

          Bạn có thể luôn loại trừ hoàn toàn một tác vụ khỏi màn hình tổng quan bằng cách thiết đặt thuộc tính <activity> , {@code android:excludeFromRecents} thành {@code true}.

          diff --git a/docs/html-intl/intl/vi/guide/components/services.jd b/docs/html-intl/intl/vi/guide/components/services.jd index 9e3e6c75eccf5..fc2a7eaeb77f7 100644 --- a/docs/html-intl/intl/vi/guide/components/services.jd +++ b/docs/html-intl/intl/vi/guide/components/services.jd @@ -199,7 +199,7 @@ con của phần tử {@code <service>} +

          Xem tham chiếu phần tử {@code <service>} để biết thêm thông tin về việc khai báo dịch vụ của bạn trong bản kê khai.

          Có các thuộc tính khác mà bạn có thể bao gồm trong phần tử {@code <service>} để @@ -605,7 +605,7 @@ tài liệu riêng về Sau khi chạy, một dịch vụ có thể thông báo cho người dùng về sự kiện bằng cách sử dụng Thông báo Cửa sổ hoặc Thông báo Thanh Trạng thái.

          -

          Thông báo cửa sổ là một thông báo xuất hiện một lúc trên bề mặt của cửa sổ hiện tại +

          Thông báo cửa sổ là một thông báo xuất hiện một lúc trên bề mặt của cửa sổ hiện tại rồi biến mất, trong khi thông báo thanh trạng thái cung cấp một biểu tượng trong thanh trạng thái cùng một thông báo, người dùng có thể chọn nó để thực hiện một hành động (chẳng hạn như bắt đầu một hoạt động).

          diff --git a/docs/html-intl/intl/vi/guide/components/tasks-and-back-stack.jd b/docs/html-intl/intl/vi/guide/components/tasks-and-back-stack.jd index 85afffff5ba54..76df1dd2e075f 100644 --- a/docs/html-intl/intl/vi/guide/components/tasks-and-back-stack.jd +++ b/docs/html-intl/intl/vi/guide/components/tasks-and-back-stack.jd @@ -190,7 +190,7 @@ trạng thái của các hoạt động của mình bằng cách sử dụng cá

          Khi hệ thống dừng một trong các hoạt động của bạn (chẳng hạn như khi một hoạt động mới bắt đầu hoặc tác vụ di chuyển về nền), hệ thống có thể hoàn toàn hủy hoạt động đó nếu nó cần khôi phục -bộ nhớ hệ thống. Khi điều này xảy ra, thông tin về trạng thái của hoạt động sẽ bị mất. Nếu điều này xảy ra, +bộ nhớ hệ thống. Khi điều này xảy ra, thông tin về trạng thái của hoạt động sẽ bị mất. Nếu điều này xảy ra, hệ thống vẫn biết rằng hoạt động có một vị trí trong ngăn xếp, nhưng khi hoạt động được đưa tới vị trí trên cùng của chồng, hệ thống phải tạo lại nó (thay vì tiếp tục). Để tránh @@ -314,7 +314,7 @@ hoạt động nằm trên cùng của ngăn xếp không phải là m

          Ví dụ, giả sử ngăn xếp của một tác vụ bao gồm hoạt động gốc A với các hoạt động B, C, và D ở trên cùng (chồng là A-B-C-D; D ở trên cùng). Một ý định đến cho loại hoạt động D. Nếu D có chế độ khởi chạy {@code "standard"} mặc định, một thực thể mới của lớp sẽ được khởi chạy và -chồng trở thành A-B-C-D-D. Tuy nhiên, nếu chế độ khởi chạy của D là {@code "singleTop"}, thực thể hiện tại +chồng trở thành A-B-C-D-D. Tuy nhiên, nếu chế độ khởi chạy của D là {@code "singleTop"}, thực thể hiện tại của D sẽ nhận ý định thông qua {@link android.app.Activity#onNewIntent onNewIntent()}, bởi nó nằm ở vị trí trên cùng của chồng—chồng vẫn là A-B-C-D. Tuy nhiên, nếu một ý định đến cho hoạt động loại B, khi đó một thực thể @@ -557,9 +557,9 @@ tác vụ mới và người dùng dành một khoảng thời gian làm việc . Lúc này, tác vụ được gửi tới nền và không hiển thị. Bây giờ, người dùng không có cách nào để quay lại tác vụ bởi nó không được biểu diễn trong trình khởi chạy ứng dụng.

          -

          Đối với những trường hợp mà bạn không muốn người dùng có thể quay lại một hoạt động, hãy đặt giá trị của phần tử +

          Đối với những trường hợp mà bạn không muốn người dùng có thể quay lại một hoạt động, hãy đặt giá trị của phần tử <activity> -, +, {@code finishOnTaskLaunch} thành {@code "true"} (xem Xóa chồng).

          diff --git a/docs/html-intl/intl/vi/guide/topics/manifest/manifest-intro.jd b/docs/html-intl/intl/vi/guide/topics/manifest/manifest-intro.jd index ca2ed26270f2b..06668b4c685c3 100644 --- a/docs/html-intl/intl/vi/guide/topics/manifest/manifest-intro.jd +++ b/docs/html-intl/intl/vi/guide/topics/manifest/manifest-intro.jd @@ -31,27 +31,27 @@ page.title=Bản kê khai Ứng dụng
        • Nó đặt tên gói Java cho ứng dụng. Tên gói đóng vai trò như một mã nhận diện duy nhất cho ứng dụng.
        • -
        • Nó mô tả các thành phần của ứng dụng — hoạt động, -dịch vụ, hàm nhận quảng bá, và trình cung cấp nội dung mà ứng dụng -được soạn bởi. Nó đặt tên các lớp triển khai từng thành phần và -công bố các khả năng của chúng (ví dụ, những tin nhắn {@link android.content.Intent -Intent} mà chúng có thể xử lý). Những khai báo này cho phép hệ thống Android +
        • Nó mô tả các thành phần của ứng dụng — hoạt động, +dịch vụ, hàm nhận quảng bá, và trình cung cấp nội dung mà ứng dụng +được soạn bởi. Nó đặt tên các lớp triển khai từng thành phần và +công bố các khả năng của chúng (ví dụ, những tin nhắn {@link android.content.Intent +Intent} mà chúng có thể xử lý). Những khai báo này cho phép hệ thống Android biết các thành phần là gì và chúng có thể được khởi chạy trong những điều kiện nào.
        • -
        • Nó xác định những tiến trình nào sẽ lưu trữ các thành phần ứng dụng.
        • +
        • Nó xác định những tiến trình nào sẽ lưu trữ các thành phần ứng dụng.
        • -
        • Nó khai báo các quyền mà ứng dụng phải có để -truy cập các phần được bảo vệ của API và tương tác với các ứng dụng khác.
        • +
        • Nó khai báo các quyền mà ứng dụng phải có để +truy cập các phần được bảo vệ của API và tương tác với các ứng dụng khác.
        • -
        • Nó cũng khai báo các quyền mà ứng dụng khác phải có để +
        • Nó cũng khai báo các quyền mà ứng dụng khác phải có để tương tác với các thành phần của ứng dụng.
        • -
        • Nó liệt kê các lớp {@link android.app.Instrumentation} cung cấp -tính năng tạo hồ sơ và các thông tin khác khi ứng dụng đang chạy. Những khai báo này -chỉ xuất hiện trong bản kê khai khi ứng dụng đang được phát triển và +
        • Nó liệt kê các lớp {@link android.app.Instrumentation} cung cấp +tính năng tạo hồ sơ và các thông tin khác khi ứng dụng đang chạy. Những khai báo này +chỉ xuất hiện trong bản kê khai khi ứng dụng đang được phát triển và thử nghiệm; chúng bị loại bỏ trước khi ứng dụng được công bố.
        • -
        • Nó khai báo mức tối thiểu của API Android mà ứng dụng +
        • Nó khai báo mức tối thiểu của API Android mà ứng dụng yêu cầu.
        • Nó liệt kê các thư viện mà ứng dụng phải được liên kết với.
        • @@ -61,12 +61,12 @@ yêu cầu.

          Cấu trúc của Tệp Bản kê khai

          -Sơ đồ bên dưới minh họa cấu trúc chung của tệp bản kê khai và mọi -phần tử mà nó có thể chứa. Từng phần tử, cùng với tất cả thuộc tính -của mình, sẽ được lập tài liệu theo dõi đầy đủ vào một tệp riêng. Để xem thông tin -chi tiết về mọi phần tử, hãy nhấp vào tên phần tử trong sơ đồ, +Sơ đồ bên dưới minh họa cấu trúc chung của tệp bản kê khai và mọi +phần tử mà nó có thể chứa. Từng phần tử, cùng với tất cả thuộc tính +của mình, sẽ được lập tài liệu theo dõi đầy đủ vào một tệp riêng. Để xem thông tin +chi tiết về mọi phần tử, hãy nhấp vào tên phần tử trong sơ đồ, trong danh sách các phần tử theo thứ tự chữ cái mà tuân theo sơ đồ, hoặc trên bất kỳ -nội dung nào khác đề cập tới tên phần tử. +nội dung nào khác đề cập tới tên phần tử.

          @@ -126,9 +126,9 @@ nội dung nào khác đề cập tới tên phần tử.
           

          -Tất cả phần tử có thể xuất hiện trong tệp bản kê khai được liệt kê ở bên dưới -theo thứ tự chữ cái. Đây là những phần tử hợp pháp duy nhất; bạn không thể -thêm các phần tử hay thuộc tính của chính mình. +Tất cả phần tử có thể xuất hiện trong tệp bản kê khai được liệt kê ở bên dưới +theo thứ tự chữ cái. Đây là những phần tử hợp pháp duy nhất; bạn không thể +thêm các phần tử hay thuộc tính của chính mình.

          @@ -158,74 +158,74 @@ thêm các phần tử hay thuộc tính của chính mình.

          - +

          Các Quy ước Tệp

          -Một số quy ước và quy tắc áp dụng chung cho tất cả các phần tử và thuộc tính +Một số quy ước và quy tắc áp dụng chung cho tất cả các phần tử và thuộc tính trong bản kê khai:

          Phần tử
          -
          Chỉ các phần tử +
          Chỉ các phần tử <manifest> và -<application> -là bắt buộc phải có, chúng đều phải có mặt và chỉ có thể xảy ra một lần. -Hầu hết các phần tử khác có thể xảy ra nhiều lần hoặc không xảy ra — mặc dù ít -nhất một vài trong số chúng phải có mặt để bản kê khai thực sự có +<application> +là bắt buộc phải có, chúng đều phải có mặt và chỉ có thể xảy ra một lần. +Hầu hết các phần tử khác có thể xảy ra nhiều lần hoặc không xảy ra — mặc dù ít +nhất một vài trong số chúng phải có mặt để bản kê khai thực sự có ý nghĩa nào đó.

          -Nếu một phần tử chứa bất kỳ nội dung nào, nó có thể chứa các phần tử khác. +Nếu một phần tử chứa bất kỳ nội dung nào, nó có thể chứa các phần tử khác. Tất cả giá trị sẽ được đặt thông qua thuộc tính, chứ không phải là dữ liệu ký tự trong một phần tử.

          Các phần tử cùng cấp thường không theo thứ tự. Ví dụ, các phần tử -<activity>, -<provider>, và -<service> -có thể được trộn lẫn với nhau theo bất kỳ trình tự nào. (Phần tử +<activity>, +<provider>, và +<service> +có thể được trộn lẫn với nhau theo bất kỳ trình tự nào. (Phần tử <activity-alias> -là trường hợp ngoại lệ đối với quy tắc này: Nó phải tuân theo -<activity> +là trường hợp ngoại lệ đối với quy tắc này: Nó phải tuân theo +<activity> , đối tượng mà nó là bí danh cho.)

          Thuộc tính
          -
          Theo cách hiểu thông thường, tất cả thuộc tính đều mang tính tùy chọn. Tuy nhiên, có một số thuộc tính -phải được quy định cho một phần tử để hoàn thành mục đích của nó. Sử dụng +
          Theo cách hiểu thông thường, tất cả thuộc tính đều mang tính tùy chọn. Tuy nhiên, có một số thuộc tính +phải được quy định cho một phần tử để hoàn thành mục đích của nó. Sử dụng tài liệu làm hướng dẫn. Đối với những thuộc tính thực sự tùy chọn, nó đề cập tới một giá trị mặc định hoặc thông báo điều gì sẽ xảy ra nếu không có một đặc tả. -

          Ngoài một số thuộc tính của phần tử -<manifest> -gốc, tất cả tên thuộc tính đều bắt đầu bằng một tiền tố {@code android:}— -ví dụ, {@code android:alwaysRetainTaskState}. Do tiền tố này -phổ dụng, tài liệu thường bỏ sót nó khi tham chiếu tới các thuộc tính +

          Ngoài một số thuộc tính của phần tử +<manifest> +gốc, tất cả tên thuộc tính đều bắt đầu bằng một tiền tố {@code android:}— +ví dụ, {@code android:alwaysRetainTaskState}. Do tiền tố này +phổ dụng, tài liệu thường bỏ sót nó khi tham chiếu tới các thuộc tính theo tên.

          Khai báo tên lớp
          -
          Nhiều thuộc tính tương ứng với các đối tượng Java, bao gồm các phần tử cho -chính ứng dụng (phần tử -<application> -) và các thành phần chính của nó — hoạt động -(<activity>), -dịch vụ -(<service>), -hàm nhận quảng bá -(<receiver>), -và trình cung cấp nội dung -(<provider>). +
          Nhiều thuộc tính tương ứng với các đối tượng Java, bao gồm các phần tử cho +chính ứng dụng (phần tử +<application> +) và các thành phần chính của nó — hoạt động +(<activity>), +dịch vụ +(<service>), +hàm nhận quảng bá +(<receiver>), +và trình cung cấp nội dung +(<provider>).

          -Nếu bạn định nghĩa một lớp con như vẫn luôn làm đối với lớp thành phần -({@link android.app.Activity}, {@link android.app.Service}, -{@link android.content.BroadcastReceiver}, và {@link android.content.ContentProvider}), -lớp con sẽ được khai báo thông qua một thuộc tính {@code name}. Tên phải bao gồm -chỉ định gói đầy đủ. +Nếu bạn định nghĩa một lớp con như vẫn luôn làm đối với lớp thành phần +({@link android.app.Activity}, {@link android.app.Service}, +{@link android.content.BroadcastReceiver}, và {@link android.content.ContentProvider}), +lớp con sẽ được khai báo thông qua một thuộc tính {@code name}. Tên phải bao gồm +chỉ định gói đầy đủ. Ví dụ, một lớp con {@link android.app.Service} có thể được khai báo như sau:

          @@ -239,12 +239,12 @@ Ví dụ, một lớp con {@link android.app.Service} có thể được khai b </manifest>

        -Tuy nhiên, do cách viết tốc ký, nếu ký tự đầu tiên của xâu là một dấu chấm, -xâu sẽ được nối với tên gói của ứng dụng (như được quy định bởi -thuộc tính của phần tử <manifest> +Tuy nhiên, do cách viết tốc ký, nếu ký tự đầu tiên của xâu là một dấu chấm, +xâu sẽ được nối với tên gói của ứng dụng (như được quy định bởi +thuộc tính của phần tử <manifest> -, package -). Cách gán sau cũng giống như trên: +, package +). Cách gán sau cũng giống như trên:

        <manifest package="com.example.project" . . . >
        @@ -257,13 +257,13 @@ thuộc tính của phần tử {@code @[gói:]kiểu:tên}

        -trong đó gói có thể được bỏ qua nếu tài nguyên nằm trong cùng gói -với ứng dụng, kiểu là kiểu của tài nguyên — chẳng hạn như "xâu" hoặc -— "vẽ được" và tên là tên nhận biết tài nguyên cụ thể. +trong đó gói có thể được bỏ qua nếu tài nguyên nằm trong cùng gói +với ứng dụng, kiểu là kiểu của tài nguyên — chẳng hạn như "xâu" hoặc +— "vẽ được" và tên là tên nhận biết tài nguyên cụ thể. Ví dụ:

        <activity android:icon="@drawable/smallPic" . . . >

        -Các giá trị từ một chủ đề được biểu diễn theo cách tương tự, nhưng với một '{@code ?}' +Các giá trị từ một chủ đề được biểu diễn theo cách tương tự, nhưng với một '{@code ?}' thay vì '{@code @}' ở đầu:

        @@ -299,8 +299,8 @@ thay vì '{@code @}' ở đầu:

        Giá trị xâu
        -
        Trường hợp giá trị của một thuộc tính là một xâu, phải sử dụng hai dấu xuyệc ngược ('{@code \\}') -để thoát các ký tự — ví dụ, '{@code \\n}' đối với +
        Trường hợp giá trị của một thuộc tính là một xâu, phải sử dụng hai dấu xuyệc ngược ('{@code \\}') +để thoát các ký tự — ví dụ, '{@code \\n}' đối với một dòng tin tức hoặc '{@code \\uxxxx}' đối với một ký tự Unicode.
        @@ -308,7 +308,7 @@ một dòng tin tức hoặc '{@code \\uxxxx}' đối với một ký tự Unico

        Các Tính năng Tệp

        -Phần sau đây mô tả cách phản ánh một số tính năng của Android +Phần sau đây mô tả cách phản ánh một số tính năng của Android trong tệp bản kê khai.

        @@ -316,23 +316,23 @@ trong tệp bản kê khai.

        Bộ lọc Ý định

        -Các thành phần cốt lõi của một ứng dụng (hoạt động, dịch vụ và hàm nhận -quảng bá) được kích hoạt bởi ý định. Ý định là một -gói thông tin (một đối tượng {@link android.content.Intent}) mô tả một -hành động mong muốn — bao gồm dữ liệu sẽ được dựa trên, thể loại của -thành phần mà sẽ thực hiện hành động, và các chỉ dẫn thích hợp khác. -Android định vị một thành phần phù hợp để hồi đáp ý định, khởi chạy -một thực thể mới của thành phần nếu cần, và chuyển cho nó đối tượng đó +Các thành phần cốt lõi của một ứng dụng (hoạt động, dịch vụ và hàm nhận +quảng bá) được kích hoạt bởi ý định. Ý định là một +gói thông tin (một đối tượng {@link android.content.Intent}) mô tả một +hành động mong muốn — bao gồm dữ liệu sẽ được dựa trên, thể loại của +thành phần mà sẽ thực hiện hành động, và các chỉ dẫn thích hợp khác. +Android định vị một thành phần phù hợp để hồi đáp ý định, khởi chạy +một thực thể mới của thành phần nếu cần, và chuyển cho nó đối tượng đó Ý định.

        -Các thành phần sẽ quảng cáo khả năng của mình — các kiểu ý định mà chúng có thể -hồi đáp — thông qua các bộ lọc ý định. Do hệ thống Android phải -tìm hiểu một thành phần có thể xử lý những ý định nào trước khi khởi chạy thành phần đó, -bộ lọc ý định được quy định trong bản kê khai như là các phần tử +Các thành phần sẽ quảng cáo khả năng của mình — các kiểu ý định mà chúng có thể +hồi đáp — thông qua các bộ lọc ý định. Do hệ thống Android phải +tìm hiểu một thành phần có thể xử lý những ý định nào trước khi khởi chạy thành phần đó, +bộ lọc ý định được quy định trong bản kê khai như là các phần tử <intent-filter> -. Một thành phần có thể có nhiều bộ lọc, mỗi bộ lọc lại mô tả +. Một thành phần có thể có nhiều bộ lọc, mỗi bộ lọc lại mô tả một khả năng khác nhau.

        @@ -344,9 +344,9 @@ thành phần.

        -Để biết thông tin về cách các đối tượng Ý định được kiểm tra thông qua bộ lọc ý định, -hãy xem tài liệu riêng có tiêu đề -Ý định +Để biết thông tin về cách các đối tượng Ý định được kiểm tra thông qua bộ lọc ý định, +hãy xem tài liệu riêng có tiêu đề +Ý định và Bộ lọc Ý định.

        @@ -354,42 +354,42 @@ và Bộ lọc Ý định.

        Biểu tượng và Nhãn

        -Nhiều phần tử có thuộc tính {@code icon} và {@code label} cho một -biểu tượng nhỏ và nhãn văn bản mà có thể được hiển thị với người dùng. Một số cũng có thuộc tính -{@code description} cho văn bản giải trình dài hơn mà cũng có thể -được hiển thị trên màn hình. Ví dụ, phần tử +Nhiều phần tử có thuộc tính {@code icon} và {@code label} cho một +biểu tượng nhỏ và nhãn văn bản mà có thể được hiển thị với người dùng. Một số cũng có thuộc tính +{@code description} cho văn bản giải trình dài hơn mà cũng có thể +được hiển thị trên màn hình. Ví dụ, phần tử <permission> -có cả ba thuộc tính này, vì thế khi người dùng được hỏi xem có -cấp quyền cho một ứng dụng yêu cầu hay không, biểu tượng thể hiện +có cả ba thuộc tính này, vì thế khi người dùng được hỏi xem có +cấp quyền cho một ứng dụng yêu cầu hay không, biểu tượng thể hiện quyền, tên của quyền, và mô tả nội dung của quyền đó đều có thể được trình bày cho người dùng xem.

        -Trong mọi trường hợp, biểu tượng và nhãn được đặt trong một phần tử chứa sẽ trở thành các thiết đặt -{@code icon} và {@code label} mặc định cho tất cả phần tử con của bộ chứa đó. -Vì thế, biểu tượng và nhãn được đặt trong phần tử -<application> -là biểu tượng và nhãn mặc định cho từng thành phần của ứng dụng. -Tương tự, biểu tượng và nhãn được đặt cho một thành phần — ví dụ, một phần tử -<activity> -— sẽ là các cài đặt mặc định cho từng phần tử -<intent-filter> +Trong mọi trường hợp, biểu tượng và nhãn được đặt trong một phần tử chứa sẽ trở thành các thiết đặt +{@code icon} và {@code label} mặc định cho tất cả phần tử con của bộ chứa đó. +Vì thế, biểu tượng và nhãn được đặt trong phần tử +<application> +là biểu tượng và nhãn mặc định cho từng thành phần của ứng dụng. +Tương tự, biểu tượng và nhãn được đặt cho một thành phần — ví dụ, một phần tử +<activity> +— sẽ là các cài đặt mặc định cho từng phần tử +<intent-filter> của thành phần đó. Nếu một phần tử -<application> -thiết đặt một nhãn, nhưng hoạt động và bộ lọc ý định của nó thì không, -nhãn ứng dụng sẽ được coi là nhãn của cả hoạt động và +<application> +thiết đặt một nhãn, nhưng hoạt động và bộ lọc ý định của nó thì không, +nhãn ứng dụng sẽ được coi là nhãn của cả hoạt động và bộ lọc ý định.

        -Biểu tượng và nhãn được đặt cho một bộ lọc ý định sẽ được sử dụng để biểu diễn một thành phần +Biểu tượng và nhãn được đặt cho một bộ lọc ý định sẽ được sử dụng để biểu diễn một thành phần bất cứ khi nào thành phần đó được trình bày với người dùng để thực hiện chức năng -mà bộ lọc đã quảng cáo. Ví dụ, một bộ lọc với các thiết đặt -"{@code android.intent.action.MAIN}" và -"{@code android.intent.category.LAUNCHER}" quảng cáo một hoạt động +mà bộ lọc đã quảng cáo. Ví dụ, một bộ lọc với các thiết đặt +"{@code android.intent.action.MAIN}" và +"{@code android.intent.category.LAUNCHER}" quảng cáo một hoạt động là hoạt động khởi đầu một ứng dụng — cụ thể, là -hoạt động sẽ được hiển thị trong trình khởi chạy ứng dụng. Vì thế, biểu tượng và nhãn +hoạt động sẽ được hiển thị trong trình khởi chạy ứng dụng. Vì thế, biểu tượng và nhãn được đặt trong bộ lọc là những nội dung được hiển thị trong trình khởi chạy.

        @@ -397,14 +397,14 @@ hoạt động sẽ được hiển thị trong trình khởi chạy ứng dụn

        Quyền

        -Một quyền là sự hạn chế giới hạn truy cập vào một phần của mã -hoặc vào dữ liệu trên thiết bị. Giới hạn này được áp đặt nhằm bảo vệ dữ liệu -và mã trọng yếu, có thể bị lạm dụng để bóp méo hoặc làm hỏng trải nghiệm người dùng. +Một quyền là sự hạn chế giới hạn truy cập vào một phần của mã +hoặc vào dữ liệu trên thiết bị. Giới hạn này được áp đặt nhằm bảo vệ dữ liệu +và mã trọng yếu, có thể bị lạm dụng để bóp méo hoặc làm hỏng trải nghiệm người dùng.

        -Mỗi quyền được nhận biết bằng một nhãn duy nhất. Thông thường, nhãn cho biết -hành động bị hạn chế. Ví dụ, sau đây là một số quyền được định nghĩa +Mỗi quyền được nhận biết bằng một nhãn duy nhất. Thông thường, nhãn cho biết +hành động bị hạn chế. Ví dụ, sau đây là một số quyền được định nghĩa bởi Android:

        @@ -418,25 +418,25 @@ Một tính năng có thể được bảo vệ bởi nhiều nhất một quy

        -Nếu một ứng dụng cần truy cập vào một tính năng được bảo vệ bởi một quyền, -nó phải khai báo rằng nó yêu cầu quyền đó cùng với một phần tử -<uses-permission> -trong bản kê khai. Lúc đó, khi ứng dụng được cài đặt trên -thiết bị, trình cài đặt sẽ xác định xem có cấp quyền -được yêu cầu hay không bằng cách kiểm tra các thẩm quyền đã ký chứng chỉ -của ứng dụng và trong một số trường hợp, bằng cách hỏi người dùng. -Nếu quyền được cấp, ứng dụng có thể sử dụng các tính năng +Nếu một ứng dụng cần truy cập vào một tính năng được bảo vệ bởi một quyền, +nó phải khai báo rằng nó yêu cầu quyền đó cùng với một phần tử +<uses-permission> +trong bản kê khai. Lúc đó, khi ứng dụng được cài đặt trên +thiết bị, trình cài đặt sẽ xác định xem có cấp quyền +được yêu cầu hay không bằng cách kiểm tra các thẩm quyền đã ký chứng chỉ +của ứng dụng và trong một số trường hợp, bằng cách hỏi người dùng. +Nếu quyền được cấp, ứng dụng có thể sử dụng các tính năng được bảo vệ. Nếu không, việc thử truy cập những tính năng đó sẽ thất bại -mà không có bất kỳ thông báo nào cho người dùng. +mà không có bất kỳ thông báo nào cho người dùng.

        -Một ứng dụng cũng có thể bảo vệ các thành phần của chính nó (hoạt động, dịch vụ, -hàm nhận quảng bá và trình cung cấp nội dung) bằng các quyền. Nó có thể sử dụng -bất kỳ quyền nào được định nghĩa bởi Android (được liệt kê trong -{@link android.Manifest.permission android.Manifest.permission}) hoặc được khai báo -bởi các ứng dụng khác. Hoặc nó có thể tự định nghĩa quyền của mình. Một quyền mới được khai báo -bằng phần tử +Một ứng dụng cũng có thể bảo vệ các thành phần của chính nó (hoạt động, dịch vụ, +hàm nhận quảng bá và trình cung cấp nội dung) bằng các quyền. Nó có thể sử dụng +bất kỳ quyền nào được định nghĩa bởi Android (được liệt kê trong +{@link android.Manifest.permission android.Manifest.permission}) hoặc được khai báo +bởi các ứng dụng khác. Hoặc nó có thể tự định nghĩa quyền của mình. Một quyền mới được khai báo +bằng phần tử <permission> . Ví dụ, một hoạt động có thể được bảo vệ như sau:

        @@ -457,43 +457,43 @@ bằng phần tử

        -Lưu ý rằng trong ví dụ này, quyền {@code DEBIT_ACCT} không chỉ -được khai báo bằng phần tử +Lưu ý rằng trong ví dụ này, quyền {@code DEBIT_ACCT} không chỉ +được khai báo bằng phần tử <permission> -, việc sử dụng quyền cũng được yêu cầu bằng phần tử -<uses-permission> -. Phải yêu cầu sử dụng quyền để các thành phần khác của -ứng dụng nhằm khởi chạy hoạt động được bảo vệ, mặc dù việc bảo vệ -do chính ứng dụng áp đặt. +, việc sử dụng quyền cũng được yêu cầu bằng phần tử +<uses-permission> +. Phải yêu cầu sử dụng quyền để các thành phần khác của +ứng dụng nhằm khởi chạy hoạt động được bảo vệ, mặc dù việc bảo vệ +do chính ứng dụng áp đặt.

        -Trong cùng ví dụ này, nếu thuộc tính {@code permission} được đặt thành một quyền -được khai báo ở nơi khác -(chẳng hạn như {@code android.permission.CALL_EMERGENCY_NUMBERS}, sẽ không -cần phải khai báo lại nó bằng một phần tử +Trong cùng ví dụ này, nếu thuộc tính {@code permission} được đặt thành một quyền +được khai báo ở nơi khác +(chẳng hạn như {@code android.permission.CALL_EMERGENCY_NUMBERS}, sẽ không +cần phải khai báo lại nó bằng một phần tử <permission> -. Tuy nhiên, sẽ vẫn cần phải yêu cầu sử dụng nó bằng -<uses-permission>. +. Tuy nhiên, sẽ vẫn cần phải yêu cầu sử dụng nó bằng +<uses-permission>.

        -Phần tử -<permission-tree> -sẽ khai báo một vùng tên cho nhóm quyền mà sẽ được định nghĩa trong -mã. Và +Phần tử +<permission-tree> +sẽ khai báo một vùng tên cho nhóm quyền mà sẽ được định nghĩa trong +mã. Và <permission-group> -sẽ định nghĩa một nhãn cho một tập hợp quyền (cả được khai báo trong bản kê khai bằng phần tử -<permission> -và được khai báo ở chỗ khác). Nó chỉ ảnh hưởng tới cách các quyền được -nhóm lại khi được trình bày với người dùng. Phần tử +sẽ định nghĩa một nhãn cho một tập hợp quyền (cả được khai báo trong bản kê khai bằng phần tử +<permission> +và được khai báo ở chỗ khác). Nó chỉ ảnh hưởng tới cách các quyền được +nhóm lại khi được trình bày với người dùng. Phần tử <permission-group> -không quy định những quyền nào thuộc về nhóm; +không quy định những quyền nào thuộc về nhóm; nó chỉ đặt cho nhóm một cái tên. Một quyền được đặt vào nhóm bằng cách gán tên nhóm với thuộc tính của phần tử -<permission> -, -permissionGroup +<permission> +, +permissionGroup .

        @@ -501,17 +501,17 @@ bằng cách gán tên nhóm với thuộc tính của phần tử

        Thư viện

        -Mọi ứng dụng đều được liên kết với thư viện Android mặc định, nó -bao gồm các gói cơ bản để xây dựng ứng dụng (bằng các lớp thông dụng -chẳng hạn như Hoạt động, Dịch vụ, Ý định, Dạng xem, Nút, Ứng dụng, Trình cung cấp Nội dung, +Mọi ứng dụng đều được liên kết với thư viện Android mặc định, nó +bao gồm các gói cơ bản để xây dựng ứng dụng (bằng các lớp thông dụng +chẳng hạn như Hoạt động, Dịch vụ, Ý định, Dạng xem, Nút, Ứng dụng, Trình cung cấp Nội dung, v.v.).

        -Tuy nhiên, một số gói nằm trong thư viện của chính mình. Nếu ứng dụng của bạn -sử dụng mã từ bất kỳ gói nào trong những gói này, nó phải công khai yêu cầu được liên kết -với chúng. Bản kê khai phải chứa một phần tử -<uses-library> -riêng để đặt tên cho từng thư viện. (Tên thư viện có thể được tìm thấy trong tài liệu +Tuy nhiên, một số gói nằm trong thư viện của chính mình. Nếu ứng dụng của bạn +sử dụng mã từ bất kỳ gói nào trong những gói này, nó phải công khai yêu cầu được liên kết +với chúng. Bản kê khai phải chứa một phần tử +<uses-library> +riêng để đặt tên cho từng thư viện. (Tên thư viện có thể được tìm thấy trong tài liệu của gói.)

        diff --git a/docs/html-intl/intl/vi/guide/topics/providers/calendar-provider.jd b/docs/html-intl/intl/vi/guide/topics/providers/calendar-provider.jd index e2ecdb32b2e81..c9d779b114834 100644 --- a/docs/html-intl/intl/vi/guide/topics/providers/calendar-provider.jd +++ b/docs/html-intl/intl/vi/guide/topics/providers/calendar-provider.jd @@ -42,7 +42,7 @@ page.title=Trình cung cấp Lịch
      • Sử dụng ý định để xem dữ liệu lịch
    - +
  • Trình điều hợp Đồng bộ
  • @@ -63,8 +63,8 @@ các thao tác trên lịch, sự kiện, người dự, nhắc nhở, v.v.

    API Trình cung cấp Lịch có thể được sử dụng bởi các ứng dụng và trình điều hợp đồng bộ. Các quy tắc thay đổi tùy vào loại chương trình đang thực hiện lệnh gọi. Tài liệu này -tập trung chủ yếu vào việc sử dụng API Trình cung cấp Lịch như một ứng dụng. Để bàn -về việc các trình điều hợp đồng bộ khác nhau như thế nào, hãy xem phần +tập trung chủ yếu vào việc sử dụng API Trình cung cấp Lịch như một ứng dụng. Để bàn +về việc các trình điều hợp đồng bộ khác nhau như thế nào, hãy xem phần Trình điều hợp Đồng bộ.

    @@ -79,17 +79,17 @@ và cũng không cần cung cấp một giao diện người dùng để xem ho

    Nội dung Cơ bản

    -

    Các trình cung cấp nội dung sẽ lưu trữ dữ liệu và cho phép truy cập +

    Các trình cung cấp nội dung sẽ lưu trữ dữ liệu và cho phép truy cập ứng dụng. Trình cung cấp nội dung được nền tảng Android giới thiệu (bao gồm Trình cung cấp Lịch) thường trình bày dữ liệu như một tập hợp gồm nhiều bảng dựa trên một mô hình cơ sở dữ liệu quan hệ, trong đó mỗi hàng là một bản ghi và mỗi cột là dữ liệu thuộc một loại và có ý nghĩa cụ thể. Thông qua API Trình cung cấp Lịch, các ứng dụng và trình điều hợp đồng bộ có thể nhận được quyền truy cập đọc/ghi vào các bảng trong cơ sở dữ liệu là nơi chứa dữ liệu lịch của người dùng.

    -

    Mọi trình cung cấp nội dung đều đưa ra một URI công khai (được bẻ dòng như một đối tượng +

    Mọi trình cung cấp nội dung đều đưa ra một URI công khai (được bẻ dòng như một đối tượng {@link android.net.Uri} ) để xác định tập dữ liệu của nó một cách duy nhất. Trình cung cấp nội dung mà kiểm soát nhiều - tập dữ liệu (nhiều bảng) sẽ đưa ra một URI riêng cho từng bảng. Tất cả + tập dữ liệu (nhiều bảng) sẽ đưa ra một URI riêng cho từng bảng. Tất cả URI cho trình cung cấp đều bắt đầu bằng xâu "content://". Điều này sẽ xác định dữ liệu là đang được kiểm soát bởi một trình cung cấp nội dung. Trình cung cấp Lịch định nghĩa các hằng số cho URI đối với từng lớp (bảng) của nó. Những URI @@ -113,26 +113,26 @@ các bảng chính và các trường liên kết chúng với nhau.

    {@link android.provider.CalendarContract.Calendars}

    - - Bảng này chứa + + Bảng này chứa thông tin riêng của lịch. Mỗi hàng trong bảng này chứa chi tiết của một lịch duy nhất, chẳng hạn như tên, màu, thông tin đồng bộ, v.v. {@link android.provider.CalendarContract.Events} - + Bảng này chứa thông tin riêng theo sự kiện. Mỗi hàng trong bảng có thông tin cho một sự kiện duy nhất—ví dụ: tiêu đề sự kiện, địa điểm, thời gian bắt đầu , thời gian kết thúc, v.v. Sự kiện có thể xảy ra một lần hoặc lặp lại nhiều lần. Người dự, -nhắc nhở, và các tính chất mở rộng được lưu trữ trong các bảng riêng. -Mỗi mục đều có một {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} +nhắc nhở, và các tính chất mở rộng được lưu trữ trong các bảng riêng. +Mỗi mục đều có một {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} tham chiếu tới {@link android.provider.BaseColumns#_ID} trong bảng Sự kiện. {@link android.provider.CalendarContract.Instances} - + Bảng này chứa thời gian bắt đầu và thời gian kết thúc của mỗi lần xảy ra một sự kiện. Mỗi hàng trong bảng này đại diện cho một lần xảy ra sự kiện. Với các sự kiện xảy ra một lần thì có một ánh xạ 1:1 @@ -141,7 +141,7 @@ của thực thể tới sự kiện. Đối với các sự kiện định kỳ {@link android.provider.CalendarContract.Attendees} - + Bảng này chứa thông tin về người dự (khách) của sự kiện. Mỗi hàng đại diện một khách duy nhất của một sự kiện. Nó quy định loại khách và phản hồi tham dự của khách @@ -149,17 +149,17 @@ cho một sự kiện. {@link android.provider.CalendarContract.Reminders} - + Bảng này chứa dữ liệu về cảnh báo/thông báo. Mỗi hàng đại diện một cảnh báo duy nhất cho một sự kiện. Một sự kiện có thể có nhiều nhắc nhở. Số nhắc nhở tối đa của một sự kiện -được quy định trong -{@link android.provider.CalendarContract.CalendarColumns#MAX_REMINDERS}, +được quy định trong +{@link android.provider.CalendarContract.CalendarColumns#MAX_REMINDERS}, được đặt bởi trình điều hợp đồng bộ đang sở hữu lịch đã cho. Nhắc nhở được quy định bằng số phút trước khi diễn ra sự kiện và có một phương pháp để xác định cách người dùng sẽ được cảnh báo. - +

    API Trình cung cấp Lịch được thiết kế để linh hoạt và mạnh mẽ. Đồng @@ -178,9 +178,9 @@ Lịch.

  • Trình điều hợp đồng bộ. Trình điều hợp đồng bộ có chức năng đồng bộ dữ liệu lịch -lên thiết bị của một người dùng bằng một máy chủ hoặc nguồn dữ liệu khác. Trong bảng +lên thiết bị của một người dùng bằng một máy chủ hoặc nguồn dữ liệu khác. Trong bảng {@link android.provider.CalendarContract.Calendars} và -{@link android.provider.CalendarContract.Events}, +{@link android.provider.CalendarContract.Events}, có các cột để cho trình điều hợp đồng bộ sử dụng. Trình cung cấp và ứng dụng không nên sửa đổi chúng. Trên thực tế, chúng không hiển thị trừ khi được truy cập như một trình điều hợp đồng bộ. Để biết thêm thông tin về @@ -209,9 +209,9 @@ phải bao gồm quyền {@link android.Manifest.permission#WRITE_CALENDAR}

    Bảng Lịch

    -

    Bảng {@link android.provider.CalendarContract.Calendars} chứa thông tin chi tiết +

    Bảng {@link android.provider.CalendarContract.Calendars} chứa thông tin chi tiết cho từng lịch. Các cột -Lịch sau có thể ghi được bởi cả ứng dụng và trình điều hợp đồng bộ. +Lịch sau có thể ghi được bởi cả ứng dụng và trình điều hợp đồng bộ. Để xem danh sách đầy đủ về các trường được hỗ trợ, hãy xem tài liệu tham khảo {@link android.provider.CalendarContract.Calendars}.

    @@ -229,7 +229,7 @@ Lịch sau có thể ghi được bởi cả ứng dụng và Trình tải. Nếu bạn đang không chỉ +không đồng bộ thay vì trên luồng chính. Để bàn thêm, hãy xem phần +Trình tải. Nếu bạn đang không chỉ đọc dữ liệu mà còn sửa đổi nó, hãy xem {@link android.content.AsyncQueryHandler}.

    @@ -268,18 +268,18 @@ public static final String[] EVENT_PROJECTION = new String[] { Calendars.CALENDAR_DISPLAY_NAME, // 2 Calendars.OWNER_ACCOUNT // 3 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1; private static final int PROJECTION_DISPLAY_NAME_INDEX = 2; private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3; - + +đồng bộ.

    Trong phần tiếp theo của ví dụ, bạn sẽ xây dựng truy vấn của mình. Lựa chọn @@ -301,58 +301,58 @@ các lịch có ACCOUNT_NAME đã xem, không chỉ các lịch mà người dùng sở hữu, hãy bỏ qua OWNER_ACCOUNT. Truy vấn sẽ trả về đối tượng {@link android.database.Cursor} mà bạn có thể sử dụng để xem xét tập kết quả được trả về bởi truy vấn -cơ sở dữ liệu. Để bàn thêm về việc sử dụng các truy vấn trong trình cung cấp nội dung, +cơ sở dữ liệu. Để bàn thêm về việc sử dụng các truy vấn trong trình cung cấp nội dung, hãy xem phần Trình cung cấp Nội dung.

    // Run query
     Cursor cur = null;
     ContentResolver cr = getContentResolver();
    -Uri uri = Calendars.CONTENT_URI;   
    -String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" 
    +Uri uri = Calendars.CONTENT_URI;
    +String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND ("
                             + Calendars.ACCOUNT_TYPE + " = ?) AND ("
                             + Calendars.OWNER_ACCOUNT + " = ?))";
     String[] selectionArgs = new String[] {"sampleuser@gmail.com", "com.google",
    -        "sampleuser@gmail.com"}; 
    -// Submit the query and get a Cursor object back. 
    +        "sampleuser@gmail.com"};
    +// Submit the query and get a Cursor object back.
     cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);

    Phần tiếp theo sử dụng con chạy để duyệt qua tập kết quả. Nó sử dụng các hằng số được thiết lập ngay từ đầu ví dụ để trả về các giá trị cho mỗi trường.

    - +
    // Use the cursor to step through the returned records
     while (cur.moveToNext()) {
         long calID = 0;
         String displayName = null;
         String accountName = null;
         String ownerName = null;
    -      
    +
         // Get the field values
         calID = cur.getLong(PROJECTION_ID_INDEX);
         displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
         accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
         ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
    -              
    +
         // Do something with the values...
     
        ...
     }
     
    - +

    Sửa đổi một lịch

    Để thực hiện cập nhật một lịch, bạn có thể cung cấp {@link android.provider.BaseColumns#_ID} của lịch hoặc dưới dạng ID được nối vào cho -Uri +Uri -({@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) +({@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) hoặc dưới dạng mục chọn đầu tiên. Lựa chọn nên bắt đầu bằng "_id=?", và selectionArg đầu tiên sẽ là {@link -android.provider.BaseColumns#_ID} của lịch. +android.provider.BaseColumns#_ID} của lịch. Bạn cũng có thể thực hiện cập nhật bằng cách mã hóa ID trong URI. Ví dụ này thay đổi tên hiển thị -của một lịch bằng cách sử dụng phương pháp +của một lịch bằng cách sử dụng phương pháp ({@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) :

    @@ -375,7 +375,7 @@ một ứng dụng cần tạo một lịch cục bộ, nó có thể làm đi chèn lịch dưới dạng một trình điều hợp đồng bộ, sử dụng {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_TYPE} của {@link android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL}. -{@link android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL} +{@link android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL} là một loại tài khoản đặc biệt dành cho các lịch không liên kết với một tài khoản thiết bị. Các lịch loại này không được đồng bộ với một máy chủ. Để bàn về trình điều hợp đồng bộ, hãy xem phần Trình điều hợp Đồng bộ.

    @@ -434,7 +434,7 @@ android.provider.CalendarContract.Events}.

    - + - + - + - - + + - + - + - + - - + - - - + @@ -514,11 +514,11 @@ java.util.TimeZone#getAvailableIDs()}. Lưu ý rằng quy tắc này không áp bạn đang chèn một sự kiện thông qua Ý định {@link android.content.Intent#ACTION_INSERT INSERT} như được mô tả trong Sử dụng ý định để chèn một sự kiện—trong kịch bản đó, một múi giờ mặc định sẽ được cung cấp. - +
  • Đối với các sự kiện không định kỳ, bạn phải đưa vào {@link android.provider.CalendarContract.EventsColumns#DTEND}.
  • - - + +
  • Đối với các sự kiện định kỳ, bạn phải đưa vào một {@link android.provider.CalendarContract.EventsColumns#DURATION} bên cạnh {@link android.provider.CalendarContract.EventsColumns#RRULE} hay {@link @@ -526,9 +526,9 @@ android.provider.CalendarContract.EventsColumns#RDATE}. Lưu ý rằng quy tắc bạn đang chèn một sự kiện thông qua Ý định {@link android.content.Intent#ACTION_INSERT INSERT} như được mô tả trong Sử dụng ý định để chèn một sự kiện—trong kịch bản đó, bạn có thể sử dụng một {@link -android.provider.CalendarContract.EventsColumns#RRULE} cùng với {@link android.provider.CalendarContract.EventsColumns#DTSTART} và {@link android.provider.CalendarContract.EventsColumns#DTEND}, và ứng dụng Lịch +android.provider.CalendarContract.EventsColumns#RRULE} cùng với {@link android.provider.CalendarContract.EventsColumns#DTSTART} và {@link android.provider.CalendarContract.EventsColumns#DTEND}, và ứng dụng Lịch sẽ tự động chuyển nó thành một thời lượng.
  • - +

    Sau đây là một ví dụ về cách chèn một sự kiện. Ví dụ này đang được thực hiện trong luồng @@ -539,8 +539,8 @@ thông tin, hãy xem phần {@link android.content.AsyncQueryHandler}.

     long calID = 3;
    -long startMillis = 0; 
    -long endMillis = 0;     
    +long startMillis = 0;
    +long endMillis = 0;
     Calendar beginTime = Calendar.getInstance();
     beginTime.set(2012, 9, 14, 7, 30);
     startMillis = beginTime.getTimeInMillis();
    @@ -561,7 +561,7 @@ Uri uri = cr.insert(Events.CONTENT_URI, values);
     
     // get the event ID that is the last element in the Uri
     long eventID = Long.parseLong(uri.getLastPathSegment());
    -// 
    +//
     // ... do something with event ID
     //
     //
    @@ -578,14 +578,14 @@ người dự hoặc nhắc nhở vào một sự kiện.

    bạn nên sử dụng một Ý định {@link android.content.Intent#ACTION_EDIT EDIT} như được mô tả trong Sử dụng ý định để chỉnh sửa một sự kiện. Tuy nhiên, nếu cần, bạn có thể chỉnh sửa sự kiện trực tiếp. Để thực hiện cập nhật -một Sự kiện, bạn có thể cung cấp _ID của sự kiện +một Sự kiện, bạn có thể cung cấp _ID của sự kiện hoặc dưới dạng ID được nối vào cho Uri ({@link -android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) -hoặc dưới dạng mục chọn đầu tiên. +android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) +hoặc dưới dạng mục chọn đầu tiên. Lựa chọn nên bắt đầu bằng "_id=?", và selectionArg đầu tiên nên là _ID của sự kiện. Bạn cũng có thể thực hiện cập nhật bằng cách sử dụng một lựa chọn không có ID. Sau đây là một ví dụ về cách cập nhật một -sự kiện. Nó thay đổi tiêu đề của sự kiện bằng cách sử dụng phương pháp +sự kiện. Nó thay đổi tiêu đề của sự kiện bằng cách sử dụng phương pháp {@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()} :

    @@ -598,7 +598,7 @@ ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); Uri updateUri = null; // The new title for the event -values.put(Events.TITLE, "Kickboxing"); +values.put(Events.TITLE, "Kickboxing"); updateUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID); int rows = getContentResolver().update(updateUri, values, null, null); Log.i(DEBUG_TAG, "Rows updated: " + rows); @@ -625,22 +625,22 @@ ContentValues values = new ContentValues(); Uri deleteUri = null; deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID); int rows = getContentResolver().delete(deleteUri, null, null); -Log.i(DEBUG_TAG, "Rows deleted: " + rows); +Log.i(DEBUG_TAG, "Rows deleted: " + rows);

    Bảng Người dự

    Mỗi hàng của bảng {@link android.provider.CalendarContract.Attendees} đại diện -cho một người dự hoặc khách duy nhất của một sự kiện. Gọi -{@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} +cho một người dự hoặc khách duy nhất của một sự kiện. Gọi +{@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} sẽ trả về một danh sách người dự cho sự kiện -với {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} đã cho. +với {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} đã cho. {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} này phải khớp với {@link -android.provider.BaseColumns#_ID} của một sự kiện cụ thể.

    +android.provider.BaseColumns#_ID} của một sự kiện cụ thể.

    Bảng sau liệt kê các trường -có thể ghi được. Khi chèn một người dự mới, bạn phải điền tất cả +có thể ghi được. Khi chèn một người dự mới, bạn phải điền tất cả ngoại trừ ATTENDEE_NAME.

    @@ -698,7 +698,7 @@ ngoại trừ ATTENDEE_NAME.

    Thêm Người dự

    Sau đây là một ví dụ về cách thêm một người dự vào một sự kiện. Lưu ý rằng -{@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} +{@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} là bắt buộc:

    @@ -718,17 +718,17 @@ Uri uri = cr.insert(Attendees.CONTENT_URI, values);
     

    Bảng Nhắc nhở

    Mỗi hàng của bảng {@link android.provider.CalendarContract.Reminders} đại diện -cho một nhắc nhở của một sự kiện. Gọi +cho một nhắc nhở của một sự kiện. Gọi {@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} sẽ trả về một danh sách nhắc nhở cho -sự kiện với +sự kiện với {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} đã cho.

    Bảng sau liệt kê các trường ghi được đối với nhắc nhở. Tất cả đều phải được đưa vào khi chèn một nhắc nhở mới. Lưu ý rằng các trình điều hợp đồng bộ quy định các loại nhắc nhở chúng hỗ trợ trong bảng {@link -android.provider.CalendarContract.Calendars}. Xem -{@link android.provider.CalendarContract.CalendarColumns#ALLOWED_REMINDERS} +android.provider.CalendarContract.Calendars}. Xem +{@link android.provider.CalendarContract.CalendarColumns#ALLOWED_REMINDERS} để biết chi tiết.

    @@ -773,16 +773,16 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values);

    Bảng Thực thể

    -

    Bảng +

    Bảng {@link android.provider.CalendarContract.Instances} chứa thời gian bắt đầu và thời gian kết thúc của các lần xảy ra một sự kiện. Mỗi hàng trong bảng này đại diện cho một lần xảy ra sự kiện. Bảng thực thể không ghi được và chỉ đưa ra một cách để truy vấn các lần xảy ra sự kiện.

    -

    Bảng sau liệt kê một số trường mà bạn có thể truy vấn đối với một thực thể. Lưu ý -rằng múi giờ được định nghĩa bởi -{@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} -và +

    Bảng sau liệt kê một số trường mà bạn có thể truy vấn đối với một thực thể. Lưu ý +rằng múi giờ được định nghĩa bởi +{@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} +và {@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_INSTANCES}.

    @@ -801,18 +801,18 @@ và - + - + - + @@ -820,16 +820,16 @@ của Lịch. - - + - +
    {@link android.provider.CalendarContract.EventsColumns#DURATION}Thời lượng của sự kiện theo định dạng RFC5545. Ví dụ, giá trị bằng "PT1H" cho biết sự kiện sẽ kéo dài một giờ và giá trị bằng "P2W" cho biết @@ -444,39 +444,39 @@ thời lượng là 2 tuần.
    {@link android.provider.CalendarContract.EventsColumns#ALL_DAY}Giá trị bằng 1 cho biết sự kiện này chiếm cả ngày, được xác định bởi múi giờ tại địa phương. Giá trị bằng 0 cho biết đó là một sự kiện thường xuyên mà có thể bắt đầu và kết thúc vào bất cứ lúc nào trong một ngày.
    {@link android.provider.CalendarContract.EventsColumns#RRULE}Quy tắc lặp lại đối với định dạng sự kiện. Ví dụ, "FREQ=WEEKLY;COUNT=10;WKST=SU". Bạn có thể tìm thêm nhiều ví dụ hơn ở đây.
    {@link android.provider.CalendarContract.EventsColumns#RDATE}Ngày lặp lại đối với sự kiện. - Bạn thường sử dụng {@link android.provider.CalendarContract.EventsColumns#RDATE} - cùng với {@link android.provider.CalendarContract.EventsColumns#RRULE} + Ngày lặp lại đối với sự kiện. + Bạn thường sử dụng {@link android.provider.CalendarContract.EventsColumns#RDATE} + cùng với {@link android.provider.CalendarContract.EventsColumns#RRULE} để định nghĩa một tập tổng hợp các trường hợp xảy ra lặp lại. Để bàn thêm, hãy xem phần RFC5545 spec.
    {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY}Xem sự kiện này được tính là thời gian bận hay là thời gian rảnh có thể được + + Xem sự kiện này được tính là thời gian bận hay là thời gian rảnh có thể được xếp lại lịch.
    {@link android.provider.CalendarContract.EventsColumns#GUESTS_CAN_MODIFY}
    {@link android.provider.CalendarContract.Instances#END_DAY}Ngày kết thúc theo lịch Julian của thực thể theo múi giờ -của Lịch. - +của Lịch. +
    {@link android.provider.CalendarContract.Instances#END_MINUTE}Phút kết thúc của thực thể được xác định từ nửa đêm theo múi giờ của Lịch.
    {@link android.provider.CalendarContract.Instances#EVENT_ID}
    {@link android.provider.CalendarContract.Instances#START_DAY}Ngày bắt đầu theo lịch Julian của thực thể theo múi giờ của Lịch. + Ngày bắt đầu theo lịch Julian của thực thể theo múi giờ của Lịch.
    {@link android.provider.CalendarContract.Instances#START_MINUTE}Phút bắt đầu của thực thể được xác định từ nửa đêm theo múi giờ -của Lịch. +của Lịch.
    @@ -840,7 +840,7 @@ của Lịch. trong URI. Trong ví dụ này, {@link android.provider.CalendarContract.Instances} có quyền truy cập trường {@link android.provider.CalendarContract.EventsColumns#TITLE} thông qua việc -triển khai giao diện {@link android.provider.CalendarContract.EventsColumns} của nó. +triển khai giao diện {@link android.provider.CalendarContract.EventsColumns} của nó. Nói cách khác, {@link android.provider.CalendarContract.EventsColumns#TITLE} được trả về qua một chế độ xem cơ sở dữ liệu, chứ không qua việc truy vấn bảng {@link @@ -853,7 +853,7 @@ public static final String[] INSTANCE_PROJECTION = new String[] { Instances.BEGIN, // 1 Instances.TITLE // 2 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_BEGIN_INDEX = 1; @@ -868,7 +868,7 @@ long startMillis = beginTime.getTimeInMillis(); Calendar endTime = Calendar.getInstance(); endTime.set(2011, 10, 24, 8, 0); long endMillis = endTime.getTimeInMillis(); - + Cursor cur = null; ContentResolver cr = getContentResolver(); @@ -883,28 +883,28 @@ ContentUris.appendId(builder, startMillis); ContentUris.appendId(builder, endMillis); // Submit the query -cur = cr.query(builder.build(), - INSTANCE_PROJECTION, - selection, - selectionArgs, +cur = cr.query(builder.build(), + INSTANCE_PROJECTION, + selection, + selectionArgs, null); - + while (cur.moveToNext()) { String title = null; long eventID = 0; - long beginVal = 0; - + long beginVal = 0; + // Get the field values eventID = cur.getLong(PROJECTION_ID_INDEX); beginVal = cur.getLong(PROJECTION_BEGIN_INDEX); title = cur.getString(PROJECTION_TITLE_INDEX); - - // Do something with the values. - Log.i(DEBUG_TAG, "Event: " + title); + + // Do something with the values. + Log.i(DEBUG_TAG, "Event: " + title); Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(beginVal); + calendar.setTimeInMillis(beginVal); DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); - Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); + Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); } } @@ -922,9 +922,9 @@ while (cur.moveToNext()) {
    {@link android.content.Intent#ACTION_VIEW VIEW}

    content://com.android.calendar/time/<ms_since_epoch>

    - Bạn cũng có thể tham khảo tới URI bằng -{@link android.provider.CalendarContract#CONTENT_URI CalendarContract.CONTENT_URI}. -Để xem một ví dụ về cách sử dụng ý định này, hãy xem Sử dụng ý định để xem dữ liệu lịch. + Bạn cũng có thể tham khảo tới URI bằng +{@link android.provider.CalendarContract#CONTENT_URI CalendarContract.CONTENT_URI}. +Để xem một ví dụ về cách sử dụng ý định này, hãy xem Sử dụng ý định để xem dữ liệu lịch. Mở lịch đến thời gian được chỉ định bởi <ms_since_epoch>. @@ -935,11 +935,11 @@ while (cur.moveToNext()) {

    content://com.android.calendar/events/<event_id>

    - - Bạn cũng có thể tham khảo tới URI bằng -{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. + + Bạn cũng có thể tham khảo tới URI bằng +{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. Để xem một ví dụ về cách sử dụng ý định này, hãy xem Sử dụng ý định để xem dữ liệu lịch. - + Xem sự kiện được chỉ định bởi <event_id>. @@ -952,12 +952,12 @@ while (cur.moveToNext()) { {@link android.content.Intent#ACTION_EDIT EDIT}

    content://com.android.calendar/events/<event_id>

    - - Bạn cũng có thể tham khảo tới URI bằng -{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. + + Bạn cũng có thể tham khảo tới URI bằng +{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. Để xem một ví dụ về cách sử dụng ý định này, hãy xem Sử dụng ý định để chỉnh sửa một sự kiện. - - + + Chỉnh sửa sự kiện được chỉ định bởi <event_id>. @@ -972,11 +972,11 @@ while (cur.moveToNext()) {
    {@link android.content.Intent#ACTION_INSERT INSERT}

    content://com.android.calendar/events

    - - Bạn cũng có thể tham khảo tới URI bằng -{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. + + Bạn cũng có thể tham khảo tới URI bằng +{@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI}. Để xem một ví dụ về cách sử dụng ý định này, hãy xem Sử dụng ý định để chèn một sự kiện. - + Tạo một sự kiện. @@ -996,7 +996,7 @@ while (cur.moveToNext()) { Tên cho sự kiện. - + {@link android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME} Thời gian bắt đầu sự kiện tính bằng mili giây trôi qua kể từ giờ epoch. @@ -1004,25 +1004,25 @@ CalendarContract.EXTRA_EVENT_BEGIN_TIME} {@link android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME} - + Thời gian kết thúc sự kiện tính bằng mili giây trôi qua kể từ giờ epoch. {@link android.provider.CalendarContract#EXTRA_EVENT_ALL_DAY CalendarContract.EXTRA_EVENT_ALL_DAY} - + Một boolean cho biết đó là một sự kiện cả ngày. Giá trị có thể bằng true hoặc false. {@link android.provider.CalendarContract.EventsColumns#EVENT_LOCATION Events.EVENT_LOCATION} - + Địa điểm của sự kiện. {@link android.provider.CalendarContract.EventsColumns#DESCRIPTION Events.DESCRIPTION} - + Mô tả sự kiện. @@ -1039,16 +1039,16 @@ Events.DESCRIPTION} {@link android.provider.CalendarContract.EventsColumns#ACCESS_LEVEL Events.ACCESS_LEVEL} - + Sự kiện là riêng tư hay công khai. {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY Events.AVAILABILITY} - + Xem sự kiện này tính là thời gian bận hay là thời gian rảnh có thể được xếp lại lịch. - - + +

    Các phần sau mô tả cách sử dụng những ý định này.

    @@ -1059,23 +1059,23 @@ Events.AVAILABILITY} Bằng cách này, ứng dụng của bạn thậm chí không cần phải có quyền {@link android.Manifest.permission#WRITE_CALENDAR} được bao gồm trong tệp bản kê khai của mình.

    - +

    Khi người dùng chạy một ứng dụng mà sử dụng cách này, ứng dụng sẽ gửi chúng tới Lịch để hoàn thành việc thêm một sự kiện. Ý định {@link android.content.Intent#ACTION_INSERT INSERT} sử dụng các trường phụ thêm để điền trước vào một mẫu bằng các chi tiết của sự kiện trong Lịch. Khi đó, người dùng có thể hủy bỏ sự kiện, chỉnh sửa mẫu nếu cần, hoặc lưu sự kiện vào lịch của mình.

    - +

    Sau đây là một đoạn mã HTML lập biểu một sự kiện vào ngày 19/1/2012, diễn ra từ 7:30 sáng đến 8:30 sáng. Lưu ý điều sau đây về đoạn mã HTML này:

      -
    • Nó quy định {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} +
    • Nó quy định {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} là Uri.
    • - +
    • Nó sử dụng các trường phụ {@link android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME} và {@link @@ -1083,10 +1083,10 @@ android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME} để điền trước thời gian của sự kiện vào mẫu. Các giá trị đối với những thời gian này phải tính bằng mili giây UTC trôi qua kể từ giờ epoch.
    • - +
    • Nó sử dụng trường phụ {@link android.content.Intent#EXTRA_EMAIL Intent.EXTRA_EMAIL} để cung cấp một danh sách người được mời phân cách bằng dấu phẩy, được chỉ định theo địa chỉ e-mail.
    • - +
     Calendar beginTime = Calendar.getInstance();
    @@ -1158,18 +1158,18 @@ truy cập Trình cung cấp Lịch:

    • Trình điều hợp đồng bộ cần chỉ định rằng nó là một trình điều hợp đồng bộ bằng cách đặt {@link android.provider.CalendarContract#CALLER_IS_SYNCADAPTER} thành true.
    • - - + +
    • Trình điều hợp đồng bộ cần cung cấp một {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_NAME} và một {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_TYPE} làm tham số truy vấn trong URI.
    • - +
    • Trình điều hợp đồng bộ có quyền truy nhập ghi vào nhiều cột hơn ứng dụng hay widget. - Ví dụ, một ứng dụng chỉ có thể sửa đổi một vài đặc điểm của một lịch, + Ví dụ, một ứng dụng chỉ có thể sửa đổi một vài đặc điểm của một lịch, chẳng hạn như tên lịch, tên hiển thị, thiết đặt hiển thị, và lịch có được đồng bộ hay không. Nếu so sánh, một trình điều hợp đồng bộ có thể truy cập không chỉ những cột đó, mà còn nhiều cột khác, chẳng hạn như màu lịch, múi giờ, mức truy nhập, địa điểm, v.v. -Tuy nhiên, trình điều hợp đồng bộ bị hạn chế đối với ACCOUNT_NAME và +Tuy nhiên, trình điều hợp đồng bộ bị hạn chế đối với ACCOUNT_NAMEACCOUNT_TYPE mà nó quy định.

    Sau đây là một phương pháp hữu ích hơn mà bạn có thể sử dụng để trả về một URI để dùng với một trình điều hợp đồng bộ:

    @@ -1180,5 +1180,5 @@ Tuy nhiên, trình điều hợp đồng bộ bị hạn chế đối với -

    Để biết việc triển khai mẫu trình điều hợp đồng bộ (không liên quan cụ thể tới Lịch), hãy xem phần +

    Để biết việc triển khai mẫu trình điều hợp đồng bộ (không liên quan cụ thể tới Lịch), hãy xem phần SampleSyncAdapter. diff --git a/docs/html-intl/intl/vi/guide/topics/providers/contacts-provider.jd b/docs/html-intl/intl/vi/guide/topics/providers/contacts-provider.jd index 2fa2ed3c9bdf9..2d94e10c7ab8a 100644 --- a/docs/html-intl/intl/vi/guide/topics/providers/contacts-provider.jd +++ b/docs/html-intl/intl/vi/guide/topics/providers/contacts-provider.jd @@ -253,7 +253,7 @@ page.title=Trình cung cấp Danh bạ Ví dụ, nếu bạn muốn ứng dụng của mình duy trì dữ liệu danh bạ cho dịch vụ dựa trên nền web của mình với miền {@code com.example.dataservice}, và tài khoản của người dùng cho dịch vụ của bạn là {@code becky.sharp@dataservice.example.com}, trước tiên, người dùng phải thêm - "loại" tài khoản ({@code com.example.dataservice}) và "tên" tài khoản + "loại" tài khoản ({@code com.example.dataservice}) và "tên" tài khoản ({@code becky.smart@dataservice.example.com}) trước khi ứng dụng của bạn có thể thêm hàng liên lạc thô. Bạn có thể giải thích yêu cầu này với người dùng bằng tài liệu, hoặc bạn có thể nhắc người dùng thêm loại và tên này, hoặc cả hai. Loại tài khoản và tên tài khoản @@ -1697,7 +1697,7 @@ startActivity(insertIntent);

    Nếu dịch vụ chấp nhận thông tin xác thực, trình xác thực có thể lưu giữ thông tin xác thực đó để sử dụng sau. Vì khuôn khổ trình xác thực bổ trợ, - {@link android.accounts.AccountManager} có thể cung cấp quyền truy cập bất kỳ token xác thực nào mà một trình xác thực + {@link android.accounts.AccountManager} có thể cung cấp quyền truy cập bất kỳ token xác thực nào mà một trình xác thực hỗ trợ và chọn hiện ra, chẳng hạn như token xác thực OAuth2.

    @@ -1821,7 +1821,7 @@ mà cung cấp dữ liệu cụ thể cho

    Dữ liệu từ Luồng Xã hội

    - Các bảng {@code android.provider.ContactsContract.StreamItems} và + Các bảng {@code android.provider.ContactsContract.StreamItems} và {@code android.provider.ContactsContract.StreamItemPhotos} quản lý dữ liệu đến từ các mạng xã hội. Bạn có thể ghi một trình điều hợp đồng bộ mà thêm dữ liệu luồng từ mạng của chính mình vào những bảng này, hoặc bạn có thể đọc dữ liệu luồng từ những bảng này và @@ -1830,7 +1830,7 @@ mà cung cấp dữ liệu cụ thể cho

    Văn bản từ luồng xã hội

    - Các mục dòng dữ liệu luôn được liên kết với một liên lạc thô. + Các mục dòng dữ liệu luôn được liên kết với một liên lạc thô. {@code android.provider.ContactsContract.StreamItemsColumns#RAW_CONTACT_ID} liên kết với giá trị _ID của liên lạc thô mới. Loại tài khoản và tên tài khoản của liên lạc thô cũng được lưu giữ trong hàng mục dòng. @@ -1934,7 +1934,7 @@ mà cung cấp dữ liệu cụ thể cho Cột này có sẵn để tương thích ngược với các phiên bản trước của Trình cung cấp Danh bạ mà đã sử dụng nó để lưu giữ ảnh. Tuy nhiên, trong phiên bản hiện tại bạn không nên sử dụng cột này để lưu giữ ảnh. Thay vào đó, hãy sử dụng - hoặc {@code android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_FILE_ID} hoặc + hoặc {@code android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_FILE_ID} hoặc {@code android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_URI} (cả hai đều được mô tả trong các điểm sau) để lưu giữ ảnh trong một tệp. Lúc này, cột này chứa một hình thu nhỏ của ảnh sẵn sàng để đọc. @@ -2344,7 +2344,7 @@ mà cung cấp dữ liệu cụ thể cho việc truy xuất thông tin ảnh. Không có lớp thuận tiện cho việc truy xuất hình thu nhỏ chính đối với một liên lạc thô, nhưng bạn có thể gửi một truy vấn tới bảng {@link android.provider.ContactsContract.Data}, chọn - {@code android.provider.BaseColumns#_ID} của liên lạc thô, + {@code android.provider.BaseColumns#_ID} của liên lạc thô, {@link android.provider.ContactsContract.CommonDataKinds.Photo#CONTENT_ITEM_TYPE Photo.CONTENT_ITEM_TYPE}, và cột {@link android.provider.ContactsContract.Data#IS_PRIMARY} để tìm hàng ảnh chính của liên lạc thô. diff --git a/docs/html-intl/intl/vi/guide/topics/providers/content-provider-basics.jd b/docs/html-intl/intl/vi/guide/topics/providers/content-provider-basics.jd index 5f868cacf5aea..808c0f712a34a 100644 --- a/docs/html-intl/intl/vi/guide/topics/providers/content-provider-basics.jd +++ b/docs/html-intl/intl/vi/guide/topics/providers/content-provider-basics.jd @@ -236,7 +236,7 @@ page.title=Nội dung Cơ bản về Trình cung cấp Nội dung Ví dụ, để có một danh sách các từ và nội dung bản địa của chúng từ Trình cung cấp Từ điển Người dùng, bạn hãy gọi {@link android.content.ContentResolver#query ContentResolver.query()}. Phương pháp {@link android.content.ContentResolver#query query()} sẽ gọi phương pháp - {@link android.content.ContentProvider#query ContentProvider.query()} được định nghĩa bởi + {@link android.content.ContentProvider#query ContentProvider.query()} được định nghĩa bởi Trình cung cấp Từ điển Người dùng. Các dòng mã sau thể hiện một lệnh gọi {@link android.content.ContentResolver#query ContentResolver.query()}:

    @@ -251,7 +251,7 @@ mCursor = getContentResolver().query(

    Bảng 2 cho biết các tham đối tới - {@link android.content.ContentResolver#query + {@link android.content.ContentResolver#query query(Uri,projection,selection,selectionArgs,sortOrder)} khớp với một câu lệnh SQL SELECT như thế nào:

    @@ -292,7 +292,7 @@ mCursor = getContentResolver().query( sortOrder ORDER BY col,col,... - sortOrder quy định thứ tự các hàng xuất hiện trong + sortOrder quy định thứ tự các hàng xuất hiện trong {@link android.database.Cursor} được trả về. @@ -344,7 +344,7 @@ Uri singleUri = ContentUris.withAppendedId(UserDictionary.Words.CONTENT_URI,4);

    Lưu ý: Các lớp {@link android.net.Uri} và {@link android.net.Uri.Builder} - chứa các phương pháp thuận tiện để xây dựng đối tượng URI định dạng tốt từ các xâu. + chứa các phương pháp thuận tiện để xây dựng đối tượng URI định dạng tốt từ các xâu. {@link android.content.ContentUris} chứa các phương pháp thuận tiện để nối các giá trị id với một URI. Đoạn mã HTML trước sử dụng {@link android.content.ContentUris#withAppendedId withAppendedId()} để nối một id với URI nội dung Từ điển Người dùng. @@ -359,8 +359,8 @@ withAppendedId()} để nối một id với URI nội dung Từ điển Ngườ

    Để giải thích rõ, đoạn mã HTML trong phần này gọi - {@link android.content.ContentResolver#query ContentResolver.query()} trên "luồng UI"". Tuy nhiên, trong - mã thực sự, bạn nên thực hiện các truy vấn không đồng bộ trên một luồng riêng. Một cách để làm + {@link android.content.ContentResolver#query ContentResolver.query()} trên "luồng UI"". Tuy nhiên, trong + mã thực sự, bạn nên thực hiện các truy vấn không đồng bộ trên một luồng riêng. Một cách để làm điều này đó là sử dụng lớp {@link android.content.CursorLoader}, nó được mô tả chi tiết hơn trong hướng dẫn Trình tải. Bênh cạnh đó, các dòng mã chỉ là đoạn mã HTML; chúng không thể hiện một ứng dụng @@ -428,7 +428,7 @@ String[] mSelectionArgs = {""};

    Đoạn mã HTML tiếp theo cho biết cách sử dụng {@link android.content.ContentResolver#query ContentResolver.query()}, bằng cách sử dụng Trình cung cấp Từ điển - Người dùng như một ví dụ. Truy vấn máy khách trình cung cấp tương tự như một truy vấn SQL, và nó chứa một + Người dùng như một ví dụ. Truy vấn máy khách trình cung cấp tương tự như một truy vấn SQL, và nó chứa một tập hợp các cột để trả về, một tập hợp các tiêu chí lựa chọn, và một thứ tự sắp xếp.

    @@ -438,8 +438,8 @@ String[] mSelectionArgs = {""};

    Biểu thức để chỉ định các hàng cần truy xuất sẽ được chia thành một mệnh đề lựa chọn và tham đối lựa chọn. Mệnh đề lựa chọn là sự kết hợp giữa các biểu thức lô-gic và biểu thức Boolean, - tên cột, và giá trị (biến mSelectionClause). Nếu bạn chỉ định - tham số thay thế được ? thay vì một giá trị, phương pháp truy vấn sẽ truy xuất giá trị + tên cột, và giá trị (biến mSelectionClause). Nếu bạn chỉ định + tham số thay thế được ? thay vì một giá trị, phương pháp truy vấn sẽ truy xuất giá trị từ mảng tham đối lựa chọn (biến mSelectionArgs).

    @@ -565,14 +565,14 @@ selectionArgs[0] = mUserInput;

    Hiển thị các kết quả truy vấn

    - Phương pháp máy khách {@link android.content.ContentResolver#query ContentResolver.query()} luôn trả về - một {@link android.database.Cursor} chứa các cột được chỉ định bởi dự thảo của - truy vấn cho các hàng khớp với các tiêu chí lựa chọn của truy vấn. Một đối tượng - {@link android.database.Cursor} cung cấp truy cập đọc ngẫu nhiên vào các hàng và cột mà nó - chứa. Bằng cách sử dụng phương pháp {@link android.database.Cursor}, bạn có thể lặp lại các hàng trong + Phương pháp máy khách {@link android.content.ContentResolver#query ContentResolver.query()} luôn trả về + một {@link android.database.Cursor} chứa các cột được chỉ định bởi dự thảo của + truy vấn cho các hàng khớp với các tiêu chí lựa chọn của truy vấn. Một đối tượng + {@link android.database.Cursor} cung cấp truy cập đọc ngẫu nhiên vào các hàng và cột mà nó + chứa. Bằng cách sử dụng phương pháp {@link android.database.Cursor}, bạn có thể lặp lại các hàng trong kết quả, xác định kiểu dữ liệu của từng cột, lấy dữ liệu ra khỏi cột, và kiểm tra các tính chất khác - của kết quả. Một số triển khai {@link android.database.Cursor} sẽ tự động - cập nhật đối tượng khi dữ liệu của trình cung cấp thay đổi, hoặc kích khởi các phương pháp trong một đối tượng quan sát + của kết quả. Một số triển khai {@link android.database.Cursor} sẽ tự động + cập nhật đối tượng khi dữ liệu của trình cung cấp thay đổi, hoặc kích khởi các phương pháp trong một đối tượng quan sát khi {@link android.database.Cursor} thay đổi, hoặc cả hai.

    @@ -703,14 +703,14 @@ if (mCursor != null) {

    Để nhận các quyền cần để truy cập một trình cung cấp, ứng dụng yêu cầu chúng bằng một phần tử <uses-permission> - trong tệp bản kê khai của nó. Khi Trình quản lý Gói Android cài đặt các ứng dụng, người dùng + trong tệp bản kê khai của nó. Khi Trình quản lý Gói Android cài đặt các ứng dụng, người dùng phải phê chuẩn tất cả quyền mà ứng dụng yêu cầu. Nếu người dùng phê chuẩn tất cả quyền, khi đó Trình quản lý Gói sẽ tiếp tục cài đặt; nếu người dùng không phê chuẩn chúng, Trình quản lý Gói sẽ hủy bỏ việc cài đặt.

    Phần tử -<uses-permission> +<uses-permission> sau yêu cầu quyền truy cập đọc vào Trình cung cấp Từ điển Người dùng:

    @@ -793,8 +793,8 @@ content://user_dictionary/words/<id_value>
         Để cập nhật một hàng, bạn sử dụng một đối tượng {@link android.content.ContentValues} với các giá trị
         được cập nhật giống như cách bạn làm với việc chèn, và các tiêu chí lựa chọn giống như cách bạn làm với truy vấn.
         Phương pháp máy khách mà bạn sử dụng là
    -    {@link android.content.ContentResolver#update ContentResolver.update()}. Bạn chỉ cần thêm 
    -    các giá trị vào đối tượng {@link android.content.ContentValues} cho các cột mà bạn đang cập nhật. Nếu bạn 
    +    {@link android.content.ContentResolver#update ContentResolver.update()}. Bạn chỉ cần thêm
    +    các giá trị vào đối tượng {@link android.content.ContentValues} cho các cột mà bạn đang cập nhật. Nếu bạn
         muốn xóa các nội dung của một cột, hãy đặt giá trị thành null.
     

    @@ -828,7 +828,7 @@ mRowsUpdated = getContentResolver().update(

    Bạn cũng nên thanh lọc thông tin đầu vào của người dùng khi gọi - {@link android.content.ContentResolver#update ContentResolver.update()}. Để tìm hiểu thêm về + {@link android.content.ContentResolver#update ContentResolver.update()}. Để tìm hiểu thêm về điều này, hãy đọc phần Bảo vệ trước mục nhập độc hại.

    Xóa dữ liệu

    @@ -858,7 +858,7 @@ mRowsDeleted = getContentResolver().delete(

    Bạn cũng nên thanh lọc thông tin đầu vào của người dùng khi gọi - {@link android.content.ContentResolver#delete ContentResolver.delete()}. Để tìm hiểu thêm về + {@link android.content.ContentResolver#delete ContentResolver.delete()}. Để tìm hiểu thêm về điều này, hãy đọc phần Bảo vệ trước mục nhập độc hại.

    @@ -929,7 +929,7 @@ mRowsDeleted = getContentResolver().delete(
  • Truy cập dữ liệu thông qua ý định: Mặc dù không thể gửi một ý định - trực tiếp tới một trình cung cấp, bạn có thể gửi một ý định tới ứng dụng của trình cung cấp đó, + trực tiếp tới một trình cung cấp, bạn có thể gửi một ý định tới ứng dụng của trình cung cấp đó, đây thường là cách tốt nhất để sửa đổi dữ liệu của trình cung cấp.
  • @@ -947,14 +947,14 @@ mRowsDeleted = getContentResolver().delete( bạn tạo một mảng đối tượng {@link android.content.ContentProviderOperation} rồi phân phối chúng tới một trình cung cấp nội dung bằng {@link android.content.ContentResolver#applyBatch ContentResolver.applyBatch()}. Bạn chuyển - quyền của trình cung cấp nội dung cho phương pháp này thay vì một URI nội dung cụ thể. + quyền của trình cung cấp nội dung cho phương pháp này thay vì một URI nội dung cụ thể. Điều này cho phép đối tượng {@link android.content.ContentProviderOperation} trong mảng có tác dụng đối với một bảng khác. Một lệnh gọi tới {@link android.content.ContentResolver#applyBatch ContentResolver.applyBatch()} trả về một mảng kết quả.

    Mô tả lớp hợp đồng {@link android.provider.ContactsContract.RawContacts} - bao gồm một đoạn mã HTML thể hiện việc chèn hàng loạt. Ứng dụng mẫu + bao gồm một đoạn mã HTML thể hiện việc chèn hàng loạt. Ứng dụng mẫu Trình quản lý Danh bạ có một ví dụ về truy cập hàng loạt trong tệp nguồn ContactAdder.java của nó. @@ -1053,7 +1053,7 @@ mRowsDeleted = getContentResolver().delete( trả kiểm soát về ứng dụng của bạn.

  • - Hoạt động của bạn trả về tiền cảnh, và hệ thống sẽ gọi phương pháp + Hoạt động của bạn trả về tiền cảnh, và hệ thống sẽ gọi phương pháp {@link android.app.Activity#onActivityResult onActivityResult()} của hoạt động của bạn. Phương pháp này nhận được ý định kết quả do hoạt động lựa chọn tạo trong ứng dụng Danh bạ. diff --git a/docs/html-intl/intl/vi/guide/topics/providers/content-provider-creating.jd b/docs/html-intl/intl/vi/guide/topics/providers/content-provider-creating.jd index 2e8579a1e92ef..fcc9b0eb60ef0 100644 --- a/docs/html-intl/intl/vi/guide/topics/providers/content-provider-creating.jd +++ b/docs/html-intl/intl/vi/guide/topics/providers/content-provider-creating.jd @@ -221,7 +221,7 @@ page.title=Tạo một Trình cung cấp Nội dung có một trình cung cấp cho phép kết hợp dữ liệu bảng và các tệp.
  • - Để làm việc với dữ liệu trên nền mạng, hãy sử dụng các lớp trong {@link java.net} và + Để làm việc với dữ liệu trên nền mạng, hãy sử dụng các lớp trong {@link java.net} và {@link android.net}. Bạn cũng có thể đồng bộ hoá dữ liệu trên nền mạng với một kho lưu trữ dữ liệu cục bộ chẳng hạn như một cơ sở dữ liệu, rồi cung cấp dữ liệu dưới dạng bảng hoặc tệp. Ứng dụng mẫu @@ -381,7 +381,7 @@ page.title=Tạo một Trình cung cấp Nội dung
    Khớp với một URI nội dung cho các bảng dataset1 - và dataset2, nhưng không khớp với URI nội dung cho table1 hoặc + và dataset2, nhưng không khớp với URI nội dung cho table1 hoặc table3.
    @@ -614,7 +614,7 @@ public class ExampleProvider extends ContentProvider {

    Triển khai phương pháp delete()

    - Phương pháp {@link android.content.ContentProvider#delete(Uri, String, String[]) delete()} + Phương pháp {@link android.content.ContentProvider#delete(Uri, String, String[]) delete()} không cần phải xóa hàng thực chất khỏi kho lưu trữ dữ liệu của bạn. Nếu bạn đang sử dụng một trình điều hợp đồng bộ với trình cung cấp của mình, bạn nên cân nhắc đánh dấu một hàng đã xóa bằng cờ "xóa" thay vì gỡ bỏ hàng một cách hoàn toàn. Trình điều hợp đồng bộ có thể @@ -626,7 +626,7 @@ public class ExampleProvider extends ContentProvider { update()} lấy cùng tham đối {@link android.content.ContentValues} được sử dụng bởi {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()}, và cùng tham đối selectionselectionArgs được sử dụng bởi - {@link android.content.ContentProvider#delete(Uri, String, String[]) delete()} và + {@link android.content.ContentProvider#delete(Uri, String, String[]) delete()} và {@link android.content.ContentProvider#query(Uri, String[], String, String[], String) ContentProvider.query()}. Điều này có thể cho phép bạn sử dụng lại mã giữa những phương pháp này.

    diff --git a/docs/html-intl/intl/vi/guide/topics/providers/document-provider.jd b/docs/html-intl/intl/vi/guide/topics/providers/document-provider.jd index 30844d7c277e2..7948fc259409d 100644 --- a/docs/html-intl/intl/vi/guide/topics/providers/document-provider.jd +++ b/docs/html-intl/intl/vi/guide/topics/providers/document-provider.jd @@ -146,7 +146,7 @@ không thay đổi giữa các lần khởi động lại thiết bị.
  • Tài liệu có thể là một tệp mở được (có một kiểu MIME cụ thể), hoặc một -thư mục chứa các tài liệu bổ sung (có kiểu MIME +thư mục chứa các tài liệu bổ sung (có kiểu MIME {@link android.provider.DocumentsContract.Document#MIME_TYPE_DIR}).
  • Mỗi tài liệu có thể có các khả năng khác nhau như được mô tả bởi @@ -177,7 +177,7 @@ có thể sử dụng kho lưu trữ đám mây dựa trên tag cho dữ liệu trực tiếp với nhau. Một máy khách yêu cầu quyền để tương tác với tệp (cụ thể là quyền đọc, chỉnh sửa, tạo hoặc xóa tệp).
  • -
  • Tương tác bắt đầu khi một ứng dụng (trong ví dụ này này một ứng dụng ảnh) thể hiện ý định +
  • Tương tác bắt đầu khi một ứng dụng (trong ví dụ này này một ứng dụng ảnh) thể hiện ý định {@link android.content.Intent#ACTION_OPEN_DOCUMENT} hoặc {@link android.content.Intent#ACTION_CREATE_DOCUMENT}. Ý định có thể bao gồm các bộ lọc để cụ thể hơn các tiêu chí—ví dụ, "cấp cho tôi tất cả tệp mở được có kiểu MIME là 'image'."
  • diff --git a/docs/html-intl/intl/vi/guide/topics/resources/accessing-resources.jd b/docs/html-intl/intl/vi/guide/topics/resources/accessing-resources.jd index b5491dcdee2c8..0054562cde1a4 100644 --- a/docs/html-intl/intl/vi/guide/topics/resources/accessing-resources.jd +++ b/docs/html-intl/intl/vi/guide/topics/resources/accessing-resources.jd @@ -259,8 +259,8 @@ tham chiếu một tài nguyên hệ thống, bạn sẽ cần đưa vào tên g android:text="@string/hello" /> -

    Lưu ý: Bạn nên sử dụng các tài nguyên xâu -vào mọi lúc, để ứng dụng của bạn có thể được bản địa hóa cho các ngôn ngữ khác. +

    Lưu ý: Bạn nên sử dụng các tài nguyên xâu +vào mọi lúc, để ứng dụng của bạn có thể được bản địa hóa cho các ngôn ngữ khác. Để biết thông tin về việc tạo các tài nguyên thay thế (chẳng hạn như xâu được bản địa hóa), hãy xem phần Cung cấp Tài nguyên Thay thế. Để được hướng dẫn đầy đủ về việc bản địa hóa ứng dụng của bạn cho các ngôn ngữ khác, diff --git a/docs/html-intl/intl/vi/guide/topics/resources/providing-resources.jd b/docs/html-intl/intl/vi/guide/topics/resources/providing-resources.jd index b733643e75cd2..ef1c6b6d4c773 100644 --- a/docs/html-intl/intl/vi/guide/topics/resources/providing-resources.jd +++ b/docs/html-intl/intl/vi/guide/topics/resources/providing-resources.jd @@ -190,7 +190,7 @@ phải được lưu ở đây, chẳng hạn như một Chú ý: Không được lưu tệp tài nguyên trực tiếp vào trong thư mục +

    Chú ý: Không được lưu tệp tài nguyên trực tiếp vào trong thư mục {@code res/}—nó sẽ gây ra lỗi với trình biên dịch.

    Để biết thêm thông tin về các loại tài nguyên, hãy xem tài liệu Các Loại Tài nguyên.

    @@ -312,7 +312,7 @@ mã mạng di động hiện tại.

    v.v.

    Ngôn ngữ được định nghĩa bằng một mã ngôn ngữ ISO - 639-1 gồm hai chữ cái, có thể theo sau là một mã khu vực + 639-1 gồm hai chữ cái, có thể theo sau là một mã khu vực ISO 3166-1-alpha-2 dài hai chữ cái (đằng trước là "{@code r}" chữ thường).

    @@ -498,7 +498,7 @@ Nhiều Màn hình.

  • {@code xlarge}: Các màn hình lớn hơn đáng kể so với màn hình HVGA mật độ trung bình truyền thống. Kích cỡ bố trí tối thiểu đối với một màn hình siêu lớn bằng xấp xỉ 720x960 đơn vị dp. Trong hầu hết trường hợp, những thiết bị có màn hình - siêu lớn sẽ quá lớn để mang trong túi và gần như là + siêu lớn sẽ quá lớn để mang trong túi và gần như là thiết bị kiểu máy tính bảng. Được thêm trong API mức 9.
  • Lưu ý: Việc sử dụng một hạn định kích cỡ không hàm ý rằng các @@ -510,7 +510,7 @@ bất kỳ tài nguyên nào phù hợp nhất.

    ứng dụng của bạn sẽ bị lỗi vào thời gian chạy (ví dụ, nếu tất cả tài nguyên bố trí được gắn thẻ hạn định {@code xlarge} nhưng thiết bị lại có màn hình kích cỡ bình thường).

    Được thêm trong API mức 4.

    - +

    Xem Hỗ trợ Nhiều Màn hình để biết thêm thông tin.

    Xem thêm trường cấu hình {@link android.content.res.Configuration#screenLayout}, @@ -530,7 +530,7 @@ hay lớn.

  • {@code notlong}: Màn hình không dài, chẳng hạn như QVGA, HVGA và VGA
  • Được thêm trong API mức 4.

    -

    Giá trị này thuần túy được dựa trên tỷ lệ khung ảnh của màn hình (màn hình "dài" sẽ rộng hơn). Nó +

    Giá trị này thuần túy được dựa trên tỷ lệ khung ảnh của màn hình (màn hình "dài" sẽ rộng hơn). Nó không liên quan tới hướng của màn hình.

    Xem thêm trường cấu hình {@link android.content.res.Configuration#screenLayout}, ở đó cho biết màn hình có dài không.

    @@ -628,7 +628,7 @@ Mức 8
  • {@code xxhdpi}: Màn hình mật độ siêu siêu cao; xấp xỉ 480dpi. Được thêm trong API Mức 16
  • {@code xxxhdpi}: Mật độ siêu siêu siêu cao sử dụng (chỉ biểu tượng trình khởi chạy, xem - ghi chú + ghi chú trong Hỗ trợ Nhiều Màn hình); xấp xỉ 640dpi. Được thêm trong API Mức 18
  • {@code nodpi}: Loại này có thể được sử dụng cho tài nguyên bitmap mà bạn không muốn được định cỡ @@ -950,7 +950,7 @@ layout-land/} cho khổ ngang và {@code layout-port/} cho khổ dọc, hãy đ cấu hình mà bạn chưa nghĩ đến, mà còn bởi các phiên bản Android mới đôi khi thêm hạn định cấu hình mà những phiên bản cũ hơn không hỗ trợ. Nếu bạn sử dụng một hạn định tài nguyên mới, nhưng vẫn duy trì tính tương thích về mã với các phiên bản cũ hơn của Android thì khi một phiên bản cũ hơn của -Android chạy trên ứng dụng của bạn, nó sẽ bị lỗi nếu bạn không cung cấp tài nguyên mặc định, do nó +Android chạy trên ứng dụng của bạn, nó sẽ bị lỗi nếu bạn không cung cấp tài nguyên mặc định, do nó không thể sử dụng tài nguyên được đặt tên bằng hạn định mới. Ví dụ, nếu {@code minSdkVersion} của bạn được đặt bằng 4, và bạn xác định tất cả tài nguyên vẽ được của mình bằng cách sử dụng chế độ ban đêm ({@code night} hoặc {@code notnight}, đã được thêm trong API Mức 8), khi đó một thiết bị API mức 4 sẽ không thể truy cập tài nguyên vẽ được của bạn và sẽ bị lỗi. Trong trường hợp diff --git a/docs/html-intl/intl/vi/guide/topics/resources/runtime-changes.jd b/docs/html-intl/intl/vi/guide/topics/resources/runtime-changes.jd index 4a9c38ccfe605..328b8ec3ad8e9 100644 --- a/docs/html-intl/intl/vi/guide/topics/resources/runtime-changes.jd +++ b/docs/html-intl/intl/vi/guide/topics/resources/runtime-changes.jd @@ -82,12 +82,12 @@ hoạt động của mình để giữ lại các đối tượng có trạng th

    Để giữ lại các đối tượng có trạng thái trong một phân đoạn trong khi thay đổi cấu hình thời gian chạy:

      -
    1. Mở rộng lớp {@link android.app.Fragment} và khai báo các tham chiếu tới đối tượng +
    2. Mở rộng lớp {@link android.app.Fragment} và khai báo các tham chiếu tới đối tượng có trạng thái của bạn.
    3. Gọi {@link android.app.Fragment#setRetainInstance(boolean)} khi phân đoạn được tạo.
    4. Thêm phân đoạn vào hoạt động của bạn.
    5. -
    6. Sử dụng {@link android.app.FragmentManager} để truy xuất phân đoạn khi hoạt động +
    7. Sử dụng {@link android.app.FragmentManager} để truy xuất phân đoạn khi hoạt động được khởi động lại.
    @@ -125,8 +125,8 @@ rò rỉ tất cả dạng xem và tài nguyên của thực thể hoạt độn có nghĩa là ứng dụng của bạn duy trì việc lưu giữ tài nguyên và chúng không thể được thu dọn bộ nhớ rác, vì thế rất nhiều bộ nhớ có thể bị mất.)

    -

    Khi đó, hãy sử dụng {@link android.app.FragmentManager} để thêm phân đoạn vào hoạt động. -Bạn có thể thu được đối tượng dữ liệu từ phân đoạn khi hoạt động bắt đầu lại trong khi +

    Khi đó, hãy sử dụng {@link android.app.FragmentManager} để thêm phân đoạn vào hoạt động. +Bạn có thể thu được đối tượng dữ liệu từ phân đoạn khi hoạt động bắt đầu lại trong khi thay đổi cấu hình thời gian chạy. Ví dụ, định nghĩa hoạt động của bạn như sau:

    @@ -168,7 +168,7 @@ public class MyActivity extends Activity {
     

    Trong ví dụ này, {@link android.app.Activity#onCreate(Bundle) onCreate()} thêm một phân đoạn hoặc khôi phục một tham chiếu đến nó. {@link android.app.Activity#onCreate(Bundle) onCreate()} cũng lưu trữ đối tượng có trạng thái bên trong thực thể phân đoạn đó. -{@link android.app.Activity#onDestroy() onDestroy()} cập nhật đối tượng có trạng thái bên trong +{@link android.app.Activity#onDestroy() onDestroy()} cập nhật đối tượng có trạng thái bên trong thực thể phân đoạn được giữ lại.

    diff --git a/docs/html-intl/intl/vi/guide/topics/ui/controls.jd b/docs/html-intl/intl/vi/guide/topics/ui/controls.jd index 37fe81c8c73a8..eda00506d0aff 100644 --- a/docs/html-intl/intl/vi/guide/topics/ui/controls.jd +++ b/docs/html-intl/intl/vi/guide/topics/ui/controls.jd @@ -69,7 +69,7 @@ kiểu điều khiển nhập liệu cụ thể, bạn có thể xây dựng Nút chọn một Tương tự như hộp kiểm, chỉ khác ở chỗ chỉ có thể chọn một tùy chọn trong nhóm. - {@link android.widget.RadioGroup RadioGroup} + {@link android.widget.RadioGroup RadioGroup}
    {@link android.widget.RadioButton RadioButton} diff --git a/docs/html-intl/intl/vi/guide/topics/ui/declaring-layout.jd b/docs/html-intl/intl/vi/guide/topics/ui/declaring-layout.jd index 6add812d89f7d..54852000a50f8 100644 --- a/docs/html-intl/intl/vi/guide/topics/ui/declaring-layout.jd +++ b/docs/html-intl/intl/vi/guide/topics/ui/declaring-layout.jd @@ -107,7 +107,7 @@ trong thư mục dự án res/layout/ Android của bạn để bi

    Nạp Tài nguyên XML

    -

    Khi bạn biên dịch ứng dụng của mình, từng tệp bố trí XML được biên dịch thành một tài nguyên +

    Khi bạn biên dịch ứng dụng của mình, từng tệp bố trí XML được biên dịch thành một tài nguyên {@link android.view.View}. Bạn nên nạp tài nguyên bố trí từ mã ứng dụng của mình, trong triển khai gọi lại {@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()} của bạn. Làm vậy bằng cách gọi {@link android.app.Activity#setContentView(int) setContentView()}, @@ -260,7 +260,7 @@ Tài nguyên Có sẵn.

    - Cặp thứ nhất được gọi là chiều rộng đo được và + Cặp thứ nhất được gọi là chiều rộng đo đượcchiều cao đo được. Những kích thước này xác định một dạng xem muốn phóng lớn bao nhiêu trong dạng xem mẹ của nó. Các kích thước đo được có thể thu được bằng cách gọi {@link android.view.View#getMeasuredWidth()} diff --git a/docs/html-intl/intl/vi/guide/topics/ui/dialogs.jd b/docs/html-intl/intl/vi/guide/topics/ui/dialogs.jd index 1fa45508ef0c3..00d523014a647 100644 --- a/docs/html-intl/intl/vi/guide/topics/ui/dialogs.jd +++ b/docs/html-intl/intl/vi/guide/topics/ui/dialogs.jd @@ -32,7 +32,7 @@ page.tags=alertdialog,dialogfragment

  • {@link android.app.DialogFragment}
  • {@link android.app.AlertDialog}
  • - +

    Xem thêm

    1. Hướng dẫn thiết kế hộp thoại
    2. @@ -235,8 +235,8 @@ AlertDialog dialog = builder.create();

    Các phương pháp set...Button() yêu cầu một tiêu đề cho nút (được cung cấp -bởi một tài nguyên xâu) và một -{@link android.content.DialogInterface.OnClickListener} có chức năng định nghĩa hành động sẽ tiến hành +bởi một tài nguyên xâu) và một +{@link android.content.DialogInterface.OnClickListener} có chức năng định nghĩa hành động sẽ tiến hành khi người dùng nhấn nút.

    Có ba nút hành động khác nhau mà bạn có thể thêm:

    @@ -248,7 +248,7 @@ khi người dùng nhấn nút.

    Trung lập
    Bạn nên sử dụng nút này khi người dùng có thể không muốn tiếp tục với hành động, nhưng không hẳn muốn hủy bỏ. Nó nằm ở giữa nút - tích cực và tiêu cực. Ví dụ, hành động có thể là "Nhắc tôi sau."
    + tích cực và tiêu cực. Ví dụ, hành động có thể là "Nhắc tôi sau."

    Bạn chỉ có thể thêm một nút mỗi loại vào một {@link @@ -271,7 +271,7 @@ Hộp thoại có tiêu đề và danh sách.

  • Danh sách nhiều lựa chọn cố định (hộp kiểm)
  • -

    Để tạo danh sách một lựa chọn như danh sách trong hình 3, +

    Để tạo danh sách một lựa chọn như danh sách trong hình 3, hãy sử dụng phương pháp {@link android.app.AlertDialog.Builder#setItems setItems()}:

    @@ -291,7 +291,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
     
     

    Vì danh sách xuất hiện trong vùng nội dung của hộp thoại, hộp thoại không thể hiển thị cả thông báo và danh sách và bạn nên đặt một tiêu đề cho hộp thoại -bằng {@link android.app.AlertDialog.Builder#setTitle setTitle()}. +bằng {@link android.app.AlertDialog.Builder#setTitle setTitle()}. Để chỉ định các mục cho danh sách, hãy gọi {@link android.app.AlertDialog.Builder#setItems setItems()}, chuyển một mảng. Hoặc, bạn có thể chỉ định một danh sách bằng cách sử dụng {@link @@ -317,11 +317,11 @@ Danh sách nhiều mục lựa chọn.

    Thêm một danh sách nhiều lựa chọn hoặc một lựa chọn cố định

    -

    Để thêm một danh sách nhiều lựa chọn (hộp kiểm) hoặc +

    Để thêm một danh sách nhiều lựa chọn (hộp kiểm) hoặc một lựa chọn (nút chọn một), hãy sử dụng các phương pháp {@link android.app.AlertDialog.Builder#setMultiChoiceItems(Cursor,String,String, -DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} hoặc -{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} hoặc +{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()} tương ứng.

    Ví dụ, sau đây là cách bạn có thể tạo một danh sách nhiều lựa chọn như @@ -346,7 +346,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { // If the user checked the item, add it to the selected items mSelectedItems.add(which); } else if (mSelectedItems.contains(which)) { - // Else, if the item is already in the array, remove it + // Else, if the item is already in the array, remove it mSelectedItems.remove(Integer.valueOf(which)); } } @@ -373,7 +373,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {

    Mặc dù cả danh sách truyền thống và danh sách có nút chọn một đều cung cấp hành động "một lựa chọn", bạn nên sử dụng {@link -android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()} nếu bạn muốn cố định lựa chọn của người dùng. Cụ thể, nếu việc mở hộp thoại lại sau này báo hiệu lựa chọn hiện tại của người dùng, khi đó bạn hãy tạo một danh sách với các nút chọn một.

    @@ -442,7 +442,7 @@ bạn nên đổi họ phông thành {@code "sans-serif"} sao cho cả hai trư một kiểu phông thống nhất.

    Để bung bố trí ra trong {@link android.support.v4.app.DialogFragment} của bạn, -hãy lấy một {@link android.view.LayoutInflater} với +hãy lấy một {@link android.view.LayoutInflater} với {@link android.app.Activity#getLayoutInflater()} và gọi {@link android.view.LayoutInflater#inflate inflate()}, trong đó tham số đầu tiên là ID tài nguyên bố trí và tham số thứ hai là một dạng xem mẹ cho bố trí. @@ -470,7 +470,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { public void onClick(DialogInterface dialog, int id) { LoginDialogFragment.this.getDialog().cancel(); } - }); + }); return builder.create(); }

    @@ -505,7 +505,7 @@ giao diện mà thông qua đó, nó sẽ chuyển các sự kiện lại cho ho
     public class NoticeDialogFragment extends DialogFragment {
    -    
    +
         /* The activity that creates an instance of this dialog fragment must
          * implement this interface in order to receive event callbacks.
          * Each method passes the DialogFragment in case the host needs to query it. */
    @@ -513,10 +513,10 @@ public class NoticeDialogFragment extends DialogFragment {
             public void onDialogPositiveClick(DialogFragment dialog);
             public void onDialogNegativeClick(DialogFragment dialog);
         }
    -    
    +
         // Use this instance of the interface to deliver action events
         NoticeDialogListener mListener;
    -    
    +
         // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
         @Override
         public void onAttach(Activity activity) {
    @@ -543,7 +543,7 @@ của hộp thoại thông qua triển khai giao diện {@code NoticeDialogListe
     public class MainActivity extends FragmentActivity
                               implements NoticeDialogFragment.NoticeDialogListener{
         ...
    -    
    +
         public void showNoticeDialog() {
             // Create an instance of the dialog fragment and show it
             DialogFragment dialog = new NoticeDialogFragment();
    @@ -656,7 +656,7 @@ public class CustomDialogFragment extends DialogFragment {
             // Inflate the layout to use as dialog or embedded fragment
             return inflater.inflate(R.layout.purchase_items, container, false);
         }
    -  
    +
         /** The system calls this only when creating the layout in a dialog. */
         @Override
         public Dialog onCreateDialog(Bundle savedInstanceState) {
    @@ -678,7 +678,7 @@ hay UI toàn màn hình, dựa vào kích cỡ màn hình:

    public void showDialog() { FragmentManager fragmentManager = getSupportFragmentManager(); CustomDialogFragment newFragment = new CustomDialogFragment(); - + if (mIsLargeLayout) { // The device is using a large layout, so show the fragment as a dialog newFragment.show(fragmentManager, "dialog"); @@ -776,7 +776,7 @@ android.support.v4.app.DialogFragment#onDismiss onDismiss()} trong {@link android.support.v4.app.DialogFragment} của mình.

    Bạn cũng có thể hủy bỏ một hộp thoại. Đây là một sự kiện đặc biệt chỉ báo người dùng -chủ ý rời khỏi hộp thoại mà không hoàn thành tác vụ. Điều này xảy ra nếu người dùng nhấn nút +chủ ý rời khỏi hộp thoại mà không hoàn thành tác vụ. Điều này xảy ra nếu người dùng nhấn nút Quay lại, chạm vào màn hình ngoài vùng hộp thoại, hoặc nếu bạn công khai gọi {@link android.app.Dialog#cancel()} trên {@link android.app.Dialog} (chẳng hạn như khi hồi đáp lại một nút "Hủy bỏ" trong hộp thoại).

    diff --git a/docs/html-intl/intl/vi/guide/topics/ui/menus.jd b/docs/html-intl/intl/vi/guide/topics/ui/menus.jd index 8e9e1c412c5a9..7950907d88bb8 100644 --- a/docs/html-intl/intl/vi/guide/topics/ui/menus.jd +++ b/docs/html-intl/intl/vi/guide/topics/ui/menus.jd @@ -83,9 +83,9 @@ không có), vì thế bạn nên chuyển sang sử dụng thanh hành động các tùy chọn khác.

    Xem phần về Tạo một Menu Tùy chọn.

    - +
    Menu ngữ cảnh và chế độ hành động theo ngữ cảnh
    - +
    Menu ngữ cảnh là một menu nổi xuất hiện khi người dùng thực hiện nhấp giữ trên một phần tử. Nó cung cấp các hành động ảnh hưởng tới nội dung hoặc khung ngữ cảnh được chọn. @@ -94,7 +94,7 @@ các mục hành động ảnh hưởng tới nội dung được chọn trong m chọn nhiều mục.

    Xem phần nói về Tạo Menu Ngữ cảnh.

    - +
    Menu bật lên
    Menu bật lên sẽ hiển thị danh sách các mục trong một danh sách thẳng đứng được neo vào dạng xem đã gọi ra menu. Nên cung cấp một phần tràn gồm các hành động liên quan tới nội dung cụ thể hoặc @@ -128,14 +128,14 @@ kích cỡ màn hình khác nhau và các cấu hình khác bằng cách tận d dự án của bạn và xây dựng menu với các phần tử sau:

    <menu>
    -
    Định nghĩa một {@link android.view.Menu}, đó là một bộ chứa các mục menu. Phần tử +
    Định nghĩa một {@link android.view.Menu}, đó là một bộ chứa các mục menu. Phần tử <menu> phải là một nút gốc cho tệp và có thể giữ một hoặc nhiều phần tử <item><group>.
    <item>
    Tạo một {@link android.view.MenuItem}, nó biểu diễn một mục đơn trong một menu. Phần tử này có thể chứa một phần tử <menu> được lồng nhau để tạo một menu con.
    - +
    <group>
    Một bộ chứa tùy chọn, vô hình cho các phần tử {@code <item>}. Nó cho phép bạn phân loại các mục menu sao cho chúng chia sẻ các tính chất như trạng thái hiện hoạt và khả năng hiển thị. Để biết thêm @@ -273,7 +273,7 @@ tính chất của chúng bằng các API {@link android.view.MenuItem}.

    Nếu bạn phát triển ứng dụng của mình cho phiên bản Android 2.3.x và thấp hơn, hệ thống gọi {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} để tạo menu tùy chọn -khi người dùng mở menu lần đầu tiên. Nếu bạn phát triển cho phiên bản Android 3.0 vào cao hơn, +khi người dùng mở menu lần đầu tiên. Nếu bạn phát triển cho phiên bản Android 3.0 vào cao hơn, hệ thống sẽ gọi {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} khi bắt đầu hoạt động để hiển thị các mục cho thanh hành động.

    @@ -346,7 +346,7 @@ trừ khi menu bị vô hiệu hóa vì lý do nào đó. Tuy nhiên, bạn ch android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} để tạo trạng thái menu ban đầu chứ không phải để thực hiện thay đổi trong vòng đời của hoạt động.

    -

    Nếu bạn muốn sửa đổi menu tùy chọn dựa trên +

    Nếu bạn muốn sửa đổi menu tùy chọn dựa trên các sự kiện xảy ra trong vòng đời của hoạt động, bạn có thể làm vậy trong phương pháp {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}. Phương pháp này chuyển cho bạn đối tượng {@link android.view.Menu} như hiện đang có để bạn có thể sửa đổi nó, @@ -363,7 +363,7 @@ trình bày trong thanh hành động. Khi một sự kiện xảy ra và bạn gọi {@link android.app.Activity#invalidateOptionsMenu invalidateOptionsMenu()} để yêu cầu hệ thống gọi {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}.

    -

    Lưu ý: +

    Lưu ý: Bạn không nên thay đổi các mục trong menu tùy chọn dựa trên {@link android.view.View} đang trong tiêu điểm. Khi ở chế độ cảm ứng (khi người dùng không sử dụng bi xoay hay d-pad), các dạng xem không thể lấy tiêu điểm, vì thế bạn không nên sử dụng tiêu điểm làm cơ sở để sửa đổi @@ -609,7 +609,7 @@ someView.setOnLongClickListener(new View.OnLongClickListener() {

    Khi bạn gọi {@link android.app.Activity#startActionMode startActionMode()}, hệ thống sẽ trả về {@link android.view.ActionMode} được tạo. Bằng cách lưu điều này trong một biến thành viên, bạn có thể -thực hiện thay đổi thanh hành động theo ngữ cảnh để hồi đáp những sự kiện khác. Trong mẫu trên, +thực hiện thay đổi thanh hành động theo ngữ cảnh để hồi đáp những sự kiện khác. Trong mẫu trên, {@link android.view.ActionMode} được sử dụng để đảm bảo rằng thực thể {@link android.view.ActionMode} không được tạo lại nếu nó đã hiện hoạt, bằng cách kiểm tra xem thành viên có rỗng không trước khi khởi động chế độ hành động.

    @@ -742,8 +742,8 @@ hiển thị một menu bật lên:

     <ImageButton
    -    android:layout_width="wrap_content" 
    -    android:layout_height="wrap_content" 
    +    android:layout_width="wrap_content"
    +    android:layout_height="wrap_content"
         android:src="@drawable/ic_overflow_holo_dark"
         android:contentDescription="@string/descr_overflow_button"
         android:onClick="showPopup" />
    @@ -1026,6 +1026,6 @@ bộ lọc ý định. Ví dụ:

    Tìm hiểu thêm về việc ghi các bộ lọc ý định trong tài liệu Ý định và Bộ lọc Ý định.

    -

    Để tham khảo một ứng dụng mẫu sử dụng kỹ thuật này, hãy xem mã mẫu +

    Để tham khảo một ứng dụng mẫu sử dụng kỹ thuật này, hãy xem mã mẫu Note Pad.

    diff --git a/docs/html-intl/intl/vi/guide/topics/ui/notifiers/notifications.jd b/docs/html-intl/intl/vi/guide/topics/ui/notifiers/notifications.jd index 5890cb331b965..8b6e1c8458c91 100644 --- a/docs/html-intl/intl/vi/guide/topics/ui/notifiers/notifications.jd +++ b/docs/html-intl/intl/vi/guide/topics/ui/notifiers/notifications.jd @@ -150,7 +150,7 @@ thông báo, bạn chuyển đối tượng {@link android.app.Notification} t {@link android.app.PendingIntent} chứa một {@link android.content.Intent} có chức năng bắt đầu một {@link android.app.Activity} trong ứng dụng của bạn. Để liên kết - {@link android.app.PendingIntent} với một cử chỉ, hãy gọi phương pháp + {@link android.app.PendingIntent} với một cử chỉ, hãy gọi phương pháp {@link android.support.v4.app.NotificationCompat.Builder} phù hợp. Ví dụ, nếu bạn muốn bắt đầu {@link android.app.Activity} khi người dùng nhấp vào văn bản thông báo trong ngăn kéo thông báo, bạn hãy thêm {@link android.app.PendingIntent} bằng cách gọi @@ -449,7 +449,7 @@ numMessages = 0;
    1. Thêm hỗ trợ cho phiên bản Android 4.0.3 và trước đó. Để làm điều này, hãy quy định mẹ của - {@link android.app.Activity} mà bạn đang bắt đầu bằng cách thêm phần tử + {@link android.app.Activity} mà bạn đang bắt đầu bằng cách thêm phần tử <meta-data> làm con của <activity>. @@ -466,9 +466,9 @@ numMessages = 0;

    2. - Cũng thêm hỗ trợ cho phiên bản Android 4.1 và sau đó. Để làm điều này, hãy thêm thuộc tính + Cũng thêm hỗ trợ cho phiên bản Android 4.1 và sau đó. Để làm điều này, hãy thêm thuộc tính android:parentActivityName - vào phần tử + vào phần tử <activity> của {@link android.app.Activity} mà bạn đang bắt đầu.
    3. diff --git a/docs/html-intl/intl/vi/guide/topics/ui/overview.jd b/docs/html-intl/intl/vi/guide/topics/ui/overview.jd index 7bd45527c7b4b..260b40d9e19c8 100644 --- a/docs/html-intl/intl/vi/guide/topics/ui/overview.jd +++ b/docs/html-intl/intl/vi/guide/topics/ui/overview.jd @@ -39,7 +39,7 @@ và một phần tử <LinearLayout> tạo ra một nhóm d
       <?xml version="1.0" encoding="utf-8"?>
       <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -              android:layout_width="fill_parent" 
      +              android:layout_width="fill_parent"
                     android:layout_height="fill_parent"
                     android:orientation="vertical" >
           <TextView android:id="@+id/text"
      @@ -60,7 +60,7 @@ bố trí.

      Để xem hướng dẫn đầy đủ về tạo bố trí UI, hãy xem phần Bố trí XML. - +

      Thành phần Giao diện Người dùng

      Bạn không phải xây dựng tất cả UI của mình bằng cách sử dụng các đối tượng {@link android.view.View} và {@link diff --git a/docs/html-intl/intl/vi/guide/topics/ui/settings.jd b/docs/html-intl/intl/vi/guide/topics/ui/settings.jd index 8e19b979d0ac1..47a5c27d1f087 100644 --- a/docs/html-intl/intl/vi/guide/topics/ui/settings.jd +++ b/docs/html-intl/intl/vi/guide/topics/ui/settings.jd @@ -82,7 +82,7 @@ cách xây dựng thiết đặt ứng dụng của bạn bằng cách sử dụ

      Hình 1. Ảnh chụp màn hình từ thiết đặt của ứng dụng -Messaging trên Android. Chọn một mục được định nghĩa bởi một {@link android.preference.Preference} +Messaging trên Android. Chọn một mục được định nghĩa bởi một {@link android.preference.Preference} sẽ mở ra một giao diện để thay đổi thiết đặt.

      @@ -121,7 +121,7 @@ sau:

      Vì thiết đặt của ứng dụng của bạn được xây dựng bằng cách sử dụng các đối tượng {@link android.preference.Preference} thay vì đối tượng -{@link android.view.View}, bạn nên sử dụng một lớp con {@link android.app.Activity} hoặc +{@link android.view.View}, bạn nên sử dụng một lớp con {@link android.app.Activity} hoặc {@link android.app.Fragment} chuyên dụng để hiển thị thiết đặt danh sách:

    - +

    Note: The entire View tree is single threaded. You must always be on the UI thread when calling any method on any View. If you are doing work on other threads and want to update the state of a View diff --git a/docs/html-intl/intl/vi/preview/api-overview.jd b/docs/html-intl/intl/vi/preview/api-overview.jd index 0e2c35e0e2286..5abc2f8829b96 100644 --- a/docs/html-intl/intl/vi/preview/api-overview.jd +++ b/docs/html-intl/intl/vi/preview/api-overview.jd @@ -336,7 +336,7 @@ của chúng — người dùng chỉ cần kéo và thả để thêm hoặ

    Chặn số

    Android N đã hỗ trợ chặn số điện thoại trong nền tảng này và cung cấp một - API khuôn khổ cho phép các nhà cung cấp dịch vụ duy trì một danh sách số bị chặn. + API khuôn khổ cho phép các nhà cung cấp dịch vụ duy trì một danh sách số bị chặn. Ứng dụng SMS mặc định, ứng dụng gọi điện mặc định và các ứng dụng của nhà cung cấp có thể đọc và ghi vào danh sách số bị chặn. Các ứng dụng khác không thể truy cập vào danh sách này.

    diff --git a/docs/html-intl/intl/vi/preview/behavior-changes.jd b/docs/html-intl/intl/vi/preview/behavior-changes.jd index 2c287504190cb..3060fbfe734f4 100644 --- a/docs/html-intl/intl/vi/preview/behavior-changes.jd +++ b/docs/html-intl/intl/vi/preview/behavior-changes.jd @@ -67,7 +67,7 @@ page.image=images/cards/card-n-changes_2x.png

    Được đưa vào Android 6.0 (Mức API 23), Chế độ Ngủ sâu cải thiện thời lượng pin bằng cách trì hoãn các hoạt động của CPU và mạng khi người dùng không cắm sạc, - không di chuyển và tắt màn hình thiết bị. Android N + không di chuyển và tắt màn hình thiết bị. Android N thêm các cải tiến cho Chế độ Ngủ sâu bằng cách sử dụng một tập con các hạn chế của CPU và mạng khi thiết bị không được cắm sạc với màn hình bị tắt, nhưng không nhất thiết phải để một chỗ, ví dụ như một thiết bị cầm tay di chuyển trong túi của người dùng. @@ -250,7 +250,7 @@ page.image=images/cards/card-n-changes_2x.png

    • Nếu một ứng dụng nhắm mục tiêu mức API 23 hoặc thấp hơn thì hệ thống sẽ tự động tắt tất cả các tiến trình chạy ngầm của ứng dụng đó. Điều này có nghĩa là nếu một người dùng rời khỏi - ứng dụng đó để mở màn hình Settings và thay đổi + ứng dụng đó để mở màn hình Settings và thay đổi Display size thì hệ thống sẽ tắt ứng dụng giống như trong trường hợp thiết bị thiếu bộ nhớ. Nếu ứng dụng đó có bất kỳ tiến trình nào chạy ở tiền cảnh thì hệ thống sẽ thông báo cho các tiến trình đó về thay đổi cấu hình như @@ -418,7 +418,7 @@ JavaVM::AttachCurrentThread from <jni.h>.
    • Giờ đây các hạn chế đặt lại mật khẩu cho người quản lý thiết bị sẽ áp dụng với người sở hữu cấu hình. Người quản lý thiết bị không thể sử dụng - DevicePolicyManager.resetPassword() được nữa để xóa mật khẩu hoặc thay đổi + DevicePolicyManager.resetPassword() được nữa để xóa mật khẩu hoặc thay đổi các mật khẩu đã đặt. Người quản lý thiết bị vẫn có thể đặt một mật khẩu nhưng chỉ khi thiết bị không có mật khẩu, mã PIN hoặc mẫu hình.
    • diff --git a/docs/html-intl/intl/vi/preview/features/background-optimization.jd b/docs/html-intl/intl/vi/preview/features/background-optimization.jd index 9554725f25a3b..39e1c15b7a8bc 100644 --- a/docs/html-intl/intl/vi/preview/features/background-optimization.jd +++ b/docs/html-intl/intl/vi/preview/features/background-optimization.jd @@ -60,7 +60,7 @@ page.image=images/cards/card-nyc_2x.jpg
      • Các ứng dụng nhắm đến Preview không nhận được truyền phát {@link - android.net.ConnectivityManager#CONNECTIVITY_ACTION} nếu chúng + android.net.ConnectivityManager#CONNECTIVITY_ACTION} nếu chúng đăng ký nhận truyền phát trong bản kê khai của chúng. Các ứng dụng đang chạy ở tiền cảnh vẫn có thể theo dõi {@code CONNECTIVITY_CHANGE} trên luồng chính của chúng bằng cách đăng ký{@link android.content.BroadcastReceiver} với {@link @@ -119,7 +119,7 @@ page.image=images/cards/card-nyc_2x.jpg

        - Khi sử dụng lớp{@link android.app.job.JobInfo.Builder JobInfo.Builder} + Khi sử dụng lớp{@link android.app.job.JobInfo.Builder JobInfo.Builder} để xây dựng đối tượng {@link android.app.job.JobInfo} của bạn, hãy áp dụng phương thức {@link android.app.job.JobInfo.Builder#setRequiredNetworkType setRequiredNetworkType()} và chuyển {@link android.app.job.JobInfo @@ -145,7 +145,7 @@ public static void scheduleJob(Context context) {

    - Khi các điều kiện cho tác vụ của bạn đã được đáp ứng, ứng dụng của bạn sẽ nhận được lệnh gọi lại để chạy + Khi các điều kiện cho tác vụ của bạn đã được đáp ứng, ứng dụng của bạn sẽ nhận được lệnh gọi lại để chạy phương thức{@link android.app.job.JobService#onStartJob onStartJob()}trong {@code JobService.class} được chỉ định. Để xem thêm các ví dụ về triển khai {@link android.app.job.JobScheduler} , hãy xem ứng dụng mẫu JobScheduler. @@ -243,7 +243,7 @@ public static void scheduleJob(Context context) {

    - Lưu ý: {@code TriggerContentUri()} không thể được sử dụng + Lưu ý: {@code TriggerContentUri()} không thể được sử dụng kết hợp với {@link android.app.job.JobInfo.Builder#setPeriodic setPeriodic()} hoặc {@link android.app.job.JobInfo.Builder#setPersisted setPersisted()}. Để tiếp tục theo dõi các thay đổi nội dung, hãy lên lịch một @@ -313,7 +313,7 @@ public static void scheduleJob(Context context) {

    Mã mẫu sau sẽ ghi đè lên phương thức {@link - android.app.job.JobService#onStartJob JobService.onStartJob()} và + android.app.job.JobService#onStartJob JobService.onStartJob()} và và ghi lại các thẩm quyền nội dung và URI đã kích hoạt tác vụ.

    @@ -357,7 +357,7 @@ public boolean onStartJob(JobParameters params) { bộ nhớ ít có thể cải thiện hiệu suất và trải nghiệm của người dùng. Loại bỏ các thành phần phụ thuộc trên các dịch vụ chạy ngầm và bộ thu truyền phát không biểu thị đã đăng ký tĩnh có thể giúp ứng dụng của bạn chạy tốt hơn trên các thiết bị như vậy. Mặc dù - N Developer Preview thực hiện các bước để giảm bớt một vài trong số các vấn đề này, nhưng chúng tôi + N Developer Preview thực hiện các bước để giảm bớt một vài trong số các vấn đề này, nhưng chúng tôi khuyến nghị bạn nên tối ưu ứng dụng của bạn để chạy hoàn toàn không cần sử dụng các tiến trình chạy ngầm này.

    diff --git a/docs/html-intl/intl/vi/preview/features/direct-boot.jd b/docs/html-intl/intl/vi/preview/features/direct-boot.jd index d95d83103b151..9b2a557c2b16a 100644 --- a/docs/html-intl/intl/vi/preview/features/direct-boot.jd +++ b/docs/html-intl/intl/vi/preview/features/direct-boot.jd @@ -81,7 +81,7 @@ bộ lọc ý định cho LOCKED_BOOT_COMPLETED trong bản kê kha </receiver>
    -

    Khi người dùng đã mở khóa thiết bị thì mọi thành phần có thể truy cập +

    Khi người dùng đã mở khóa thiết bị thì mọi thành phần có thể truy cập cả bộ nhớ lưu trữ mã hóa thiết bị lẫn bộ nhớ lưu trữ mã hóa thông tin xác thực.

    Truy cập Bộ nhớ Lưu trữ Mã hóa của Thiết bị

    @@ -89,7 +89,7 @@ cả bộ nhớ lưu trữ mã hóa thiết bị lẫn bộ nhớ lưu trữ mã

    Để truy cập bộ nhớ lưu trữ mã hóa thiết bị, hãy tạo một thực thể {@link android.content.Context} thứ hai bằng cách gọi Context.createDeviceEncryptedStorageContext(). Tất cả các lệnh gọi -API bộ nhớ lưu trữ đều sử dụng bối cảnh này để truy cập bộ nhớ lưu trữ mã hóa thiết bị. +API bộ nhớ lưu trữ đều sử dụng bối cảnh này để truy cập bộ nhớ lưu trữ mã hóa thiết bị. Ví dụ sau sẽ truy cập bộ nhớ lưu trữ mã hóa của thiết bị và mở một tệp dữ liệu ứng dụng có sẵn:

    diff --git a/docs/html-intl/intl/vi/preview/features/icu4j-framework.jd b/docs/html-intl/intl/vi/preview/features/icu4j-framework.jd index 63f6825df8bae..ffb57994a8815 100644 --- a/docs/html-intl/intl/vi/preview/features/icu4j-framework.jd +++ b/docs/html-intl/intl/vi/preview/features/icu4j-framework.jd @@ -51,7 +51,7 @@ page.image=images/cards/card-nyc_2x.jpg

    Android N cung cấp một tập nhỏ các API ICU4J thông qua - gói android.icu thay vì gói com.ibm.icu. + gói android.icu thay vì gói com.ibm.icu. Khuôn khổ Android có thể chọn không cung cấp các API ICU4J vì nhiều lý do; ví dụ, Android N không cung cấp một số API bị loại bỏ hoặc những API chưa được đội ngũ ICU công bố là @@ -79,7 +79,7 @@ Khuôn khổ Android có thể chọn không

    • Các API khuôn khổ Android ICU4J không có tất cả các API của ICU4J.
    • Các nhà phát triển NDK cần biết rằng ICU4C Android không được hỗ trợ.
    • -
    • Các API trong khuôn khổ Android không thay thế hỗ trợ của Android cho +
    • Các API trong khuôn khổ Android không thay thế hỗ trợ của Android cho việc bản địa hóa bằng các tài nguyên.
    @@ -87,7 +87,7 @@ các tài nguyên.

    Chuyển nhập sang gói android.icu từ com.ibm.icu

    - Nếu bạn đã sử dụng các API ICU4J trong ứng dụng và + Nếu bạn đã sử dụng các API ICU4J trong ứng dụng và các API android.icu đáp ứng yêu cầu của bạn thì việc chuyển nhập sang các API của khuôn khổ đòi hỏi bạn phải thay đổi thành phần nhập vào của Java từ com.ibm.icu sang android.icu. Khi đó bạn có thể diff --git a/docs/html-intl/intl/vi/preview/features/multi-window.jd b/docs/html-intl/intl/vi/preview/features/multi-window.jd index 485bc284786f1..5b2cb54cbc1c4 100644 --- a/docs/html-intl/intl/vi/preview/features/multi-window.jd +++ b/docs/html-intl/intl/vi/preview/features/multi-window.jd @@ -33,7 +33,7 @@ page.keywords="multi-window", "android N", "split screen", "free-form"

    Nếu bạn dựng ứng dụng của bạn bằng N Preview SDK, bạn có thể cấu hình cách ứng dụng của bạn - xử lý hiển thị đa cửa sổ. Ví dụ, bạn có thể quy định + xử lý hiển thị đa cửa sổ. Ví dụ, bạn có thể quy định các kích thước tối thiểu cho phép của hoạt động của bạn. Bạn cũng có thể vô hiệu hóa hiển thị đa cửa sổ cho ứng dụng của bạn, đảm bảo rằng hệ thống chỉ hiển thị ứng dụng của bạn trong chế độ toàn màn hình. @@ -117,7 +117,7 @@ page.keywords="multi-window", "android N", "split screen", "free-form"

    Lưu ý: Trong chế độ đa cửa sổ, một ứng dụng có thể trong trạng thái - tạm dừng và vẫn hiển thị với người dùng. Ứng dụng có thể cần tiếp tục + tạm dừng và vẫn hiển thị với người dùng. Ứng dụng có thể cần tiếp tục các hoạt động của nó thậm chí trong khi đamg bị tạm dừng. Ví dụ, một ứng dụng phát video đang ở trong chế độ tạm dừng nhưng vẫn hiển thị thì sẽ tiếp tục hiển thị video của nó. Vì lý do này, chúng tôi đề nghị các hoạt động phát video không tạm dừng @@ -129,13 +129,13 @@ page.keywords="multi-window", "android N", "split screen", "free-form"

    Khi người dùng đặt một ứng dụng vào trong chế độ đa cửa sổ, hệ thống sẽ thông báo về - hoạt động thay đổi cấu hình đó, như được quy định trong Xử lý Thay đổi + hoạt động thay đổi cấu hình đó, như được quy định trong Xử lý Thay đổi Thời gian chạy. Về cơ bản, thay đổi này có ngụ ý về vòng đời hoạt động tương tự vì khi hệ thống thông báo cho ứng dụng rằng thiết bị đã chuyển từ chế độ hướng dọc sang chế độ ngang, ngoại trừ trường hợp các kích thước của thiết bị đã được thay đổi thay vì chỉ bị hoán đổi. Như đã thảo luận trong phần Xử lý Thay đổi Thời gian chạy, hoạt động của bạn có thể tự xử lý thay đổi cấu hình này, hoặc nó - có thể cho phép hệ thống hủy hoạt động này và tạo lại nó với + có thể cho phép hệ thống hủy hoạt động này và tạo lại nó với các kích thước mới.

    @@ -207,7 +207,7 @@ android:supportsPictureInPicture=["true" | "false"]

    Thuộc tính bố trí

    - Với Android N, phần tử bản kê khai <layout> + Với Android N, phần tử bản kê khai <layout> có hỗ trợ một số thuộc tính sẽ ảnh hưởng đến cách hoạt động có hành vi như thế nào trong chế độ đa cửa sổ:

    @@ -244,7 +244,7 @@ android:supportsPictureInPicture=["true" | "false"]
    Chiều cao và chiều rộng tối thiểu cho hoạt động trong cả chế độ chia màn hình - và chế độ hình dạng tự do. Nếu người dùng di chuyển thanh phân chia trong chế độ chia màn hình + và chế độ hình dạng tự do. Nếu người dùng di chuyển thanh phân chia trong chế độ chia màn hình để làm cho hoạt động nhỏ hơn mức tối thiểu quy định, hệ thống sẽ cắt xén hoạt động đó thành kích cỡ mà người dùng yêu cầu.
    @@ -295,7 +295,7 @@ android:supportsPictureInPicture=["true" | "false"]

    Các phương thức mới sau đây đã được thêm vào lớp {@link android.app.Activity} - để hỗ trợ hiển thị đa cửa sổ. Để biết chi tiết về mỗi phương thức, xem + để hỗ trợ hiển thị đa cửa sổ. Để biết chi tiết về mỗi phương thức, xem Tham chiếu N Preview SDK.

    @@ -560,7 +560,7 @@ android:supportsPictureInPicture=["true" | "false"]
  • Thực hiện một vài thao tác thay đổi kích cỡ nối tiếp nhau thật nhanh. Xác minh rằng ứng dụng - của bạn không bị lỗi hoặc bị rò rỉ bộ nhớ. Để biết thông tin về kiểm tra việc sử dụng bộ nhớ của + của bạn không bị lỗi hoặc bị rò rỉ bộ nhớ. Để biết thông tin về kiểm tra việc sử dụng bộ nhớ của ứng dụng, xem Kiểm tra Sử dụng RAM của bạn.
  • diff --git a/docs/html-intl/intl/vi/preview/features/notification-updates.jd b/docs/html-intl/intl/vi/preview/features/notification-updates.jd index d80cf6c08f5eb..f60646a46f43d 100644 --- a/docs/html-intl/intl/vi/preview/features/notification-updates.jd +++ b/docs/html-intl/intl/vi/preview/features/notification-updates.jd @@ -37,7 +37,7 @@ hiện có để hỗ trợ trả lời giữa dòng trên thiết bị cầm ta thông báo, từng thông báo một từ khu vực hiển thị thông báo.

    -

    Cuối cùng, Android N cũng thêm các API mới cho phép bạn tận dụng các trang trí +

    Cuối cùng, Android N cũng thêm các API mới cho phép bạn tận dụng các trang trí của hệ thống trong các dạng xem thông báo tùy chỉnh của ứng dụng của bạn. Các API này giúp đảm bảo rằng dạng xem thông báo có chung một cách trình bày nhất quán với các mẫu tiêu chuẩn.

    @@ -69,9 +69,9 @@ của thông báo. Trên thiết bị cầm tay, hành động trả lời giữ

      -
    1. Tạo thực thể{@link android.support.v4.app.RemoteInput.Builder} +
    2. Tạo thực thể{@link android.support.v4.app.RemoteInput.Builder} mà bạn có thể thêm vào hành động -thông báo của bạn. Hàm dựng của lớp này sẽ chấp nhận xâu mà hệ thống sử dụng làm khóa +thông báo của bạn. Hàm dựng của lớp này sẽ chấp nhận xâu mà hệ thống sử dụng làm khóa cho nhập liệu văn bản. Sau đó, ứng dụng cầm tay của bạn sử dụng khóa đó để truy xuất văn bản nhập liệu. diff --git a/docs/html-intl/intl/vi/preview/features/picture-in-picture.jd b/docs/html-intl/intl/vi/preview/features/picture-in-picture.jd index 4b3cb400f72ea..65799dbb0ca30 100644 --- a/docs/html-intl/intl/vi/preview/features/picture-in-picture.jd +++ b/docs/html-intl/intl/vi/preview/features/picture-in-picture.jd @@ -128,7 +128,7 @@ các hành động ở chế độ PIP trên thanh điều khiển và sử dụ video. Hãy xóa các phần tử UI trước khi hoạt động của bạn vào chế độ PIP, và khôi phục các phần tử này khi hoạt động quay lại chế độ toàn màn hình. Ghi đè phương thức Activity.onPictureInPictureChanged() hoặc -Fragment.onPictureInPictureChanged() và bật hoặc +Fragment.onPictureInPictureChanged() và bật hoặc tắt các phần tử UI khi cần thiết, ví dụ:

      @@ -150,7 +150,7 @@ public void onPictureInPictureChanged(boolean inPictureInPicture) {
       

      Khi hoạt động của bạn chuyển sang chế độ PIP thì hệ thống sẽ coi hoạt động đó đang ở trong trạng thái tạm dừng và sẽ gọi phương thức onPause() của hoạt động. Việc phát lại video không nên được tạm dừng và cần được tiếp tục phát nếu hoạt động -bị tạm dừng do chế độ PIP. Hãy kiểm tra chế độ PIP trong phương thức +bị tạm dừng do chế độ PIP. Hãy kiểm tra chế độ PIP trong phương thức onPause() của hoạt động và xử lý việc phát lại cho phù hợp, ví dụ:

      diff --git a/docs/html-intl/intl/vi/preview/overview.jd b/docs/html-intl/intl/vi/preview/overview.jd index a71bf61b34ab6..f7094896a4e49 100644 --- a/docs/html-intl/intl/vi/preview/overview.jd +++ b/docs/html-intl/intl/vi/preview/overview.jd @@ -175,7 +175,7 @@ page.tags="preview", "developer", "android"

      - Tại Preview 4 và 5 bạn sẽ được sử dụng các + Tại Preview 4 và 5 bạn sẽ được sử dụng các API và SDK N cuối cùng để phát triển, và cả các ảnh hệ thống gần hoàn thiện để kiểm thử các hành vi, tính năng của hệ thống. Android N sẽ cung cấp một mức API chuẩn vào thời điểm này. Bạn có thể tiến hành kiểm thử khả năng tương thích cuối cùng đối với các ứng dụng @@ -321,7 +321,7 @@ Android N có Hành vi chỉ ra cho bạn các phần chính yếu để kiểm thử.

    3. Tổng quan về các API mới, bao gồm một phần Tổng quan về API, bản tải xuống được Tham khảo - API và các hướng dẫn chi tiết cho nhà phát triển đối với các tính năng quan trọng như + API và các hướng dẫn chi tiết cho nhà phát triển đối với các tính năng quan trọng như hỗ trợ đa cửa sổ, thông báo gộp, hỗ trợ đa bản địa và các tính năng khác.
    4. Mã mẫu trong đó minh họa cách hỗ trợ các quyền và tính năng mới. diff --git a/docs/html-intl/intl/vi/training/material/animations.jd b/docs/html-intl/intl/vi/training/material/animations.jd index e93c99d64508f..9299d3c931a89 100644 --- a/docs/html-intl/intl/vi/training/material/animations.jd +++ b/docs/html-intl/intl/vi/training/material/animations.jd @@ -21,7 +21,7 @@ page.title=Định nghĩa Hoạt hình Tùy chỉnh -

      Hoạt hình theo phong cách material design phản hồi hành động của người dùng và cung cấp +

      Hoạt hình theo phong cách material design phản hồi hành động của người dùng và cung cấp tính liên tục trực quan khi người dùng tương tác với ứng dụng của bạn. Giao diện material cung cấp một số hoạt hình mặc định cho các nút và chuyển tiếp hoạt động, và Android 5.0 (API mức 21) và cao hơn cho phép bạn tùy chỉnh những hoạt hình này và tạo các hoạt hình mới:

      @@ -160,7 +160,7 @@ trung tâm.
    5. Chuyển tiếp phần tử chung xác định các dạng xem chung giữa hai hoạt động sẽ chuyển tiếp như thế nào giữa những hoạt động này. Ví dụ, nếu hai hoạt động có cùng -hình ảnh ở các vị trí và kích cỡ khác nhau, chuyển tiếp phần tử chung changeImageTransform +hình ảnh ở các vị trí và kích cỡ khác nhau, chuyển tiếp phần tử chung changeImageTransform sẽ thể hiện và co giãn hình ảnh một cách mượt mà giữa những hoạt động này.
    6. @@ -329,7 +329,7 @@ thay vì {@link android.app.Activity#finish Activity.finish()}.

      Để tạo một hoạt hình chuyển tiếp cảnh giữa hai hoạt động có nhiều hơn một phần tử chung, hãy định nghĩa các phần tử chung trong cả hai bố trí bằng thuộc tính android:transitionName - (hoặc sử dụng phương thức {@link android.view.View#setTransitionName View.setTransitionName()} + (hoặc sử dụng phương thức {@link android.view.View#setTransitionName View.setTransitionName()} trong cả hai hoạt động), và tạo một đối tượng {@link android.app.ActivityOptions} như sau:

      diff --git a/docs/html-intl/intl/vi/training/material/compatibility.jd b/docs/html-intl/intl/vi/training/material/compatibility.jd
      index e19a745dd9b98..2f5c0160f6757 100644
      --- a/docs/html-intl/intl/vi/training/material/compatibility.jd
      +++ b/docs/html-intl/intl/vi/training/material/compatibility.jd
      @@ -94,7 +94,7 @@ r21 và cao hơn gồm những tính năng material design sau:

      Bảng màu

      -

      Để có được các kiểu phong cách material design và tùy chỉnh bảng màu bằng Thư viện Hỗ trợ v7 +

      Để có được các kiểu phong cách material design và tùy chỉnh bảng màu bằng Thư viện Hỗ trợ v7 của Android, hãy áp dụng một trong các chủ đề Theme.AppCompat:

      diff --git a/docs/html-intl/intl/vi/training/material/drawables.jd b/docs/html-intl/intl/vi/training/material/drawables.jd
      index 175e77d629e8a..db69412c544e0 100644
      --- a/docs/html-intl/intl/vi/training/material/drawables.jd
      +++ b/docs/html-intl/intl/vi/training/material/drawables.jd
      @@ -57,7 +57,7 @@ Lớp này trích xuất những màu nổi bật sau:

    7. Sáng lặng
    8. -

      Để trích xuất những màu này, hãy chuyển một đối tượng {@link android.graphics.Bitmap} cho phương thức tĩnh +

      Để trích xuất những màu này, hãy chuyển một đối tượng {@link android.graphics.Bitmap} cho phương thức tĩnh {@link android.support.v7.graphics.Palette#generate Palette.generate()} trong luồng chạy ngầm nơi bạn tải hình ảnh của mình. Nếu bạn không thể sử dụng luồng đó, hãy gọi phương thức {@link android.support.v7.graphics.Palette#generateAsync Palette.generateAsync()} và diff --git a/docs/html-intl/intl/vi/training/material/get-started.jd b/docs/html-intl/intl/vi/training/material/get-started.jd index 9e612ad10c07c..45d7c09e3e0b1 100644 --- a/docs/html-intl/intl/vi/training/material/get-started.jd +++ b/docs/html-intl/intl/vi/training/material/get-started.jd @@ -94,7 +94,7 @@ bố trí của bạn, hãy đặc biệt chú ý tới điều sau đây:

      Quy định Độ cao trong Dạng xem của Bạn

      -

      Dạng xem có thể đổ bóng và giá trị độ cao của một dạng xem +

      Dạng xem có thể đổ bóng và giá trị độ cao của một dạng xem xác định kích cỡ bóng và thứ tự vẽ của nó. Để đặt độ cao của một dạng xem, hãy sử dụng thuộc tính android:elevation trong bố trí của bạn:

      @@ -122,7 +122,7 @@ chạm.

      {@link android.support.v7.widget.RecyclerView} là một phiên bản dễ ghép nối hơn của {@link android.widget.ListView} có hỗ trợ các kiểu bố trí khác nhau và cung cấp những cải tiến về hiệu năng. {@link android.support.v7.widget.CardView} cho phép bạn hiện các mẩu thông tin bên trong thẻ với -một diện mạo nhất quán giữa các ứng dụng. Ví dụ về mã sau đây minh họa cách thêm +một diện mạo nhất quán giữa các ứng dụng. Ví dụ về mã sau đây minh họa cách thêm {@link android.support.v7.widget.CardView} vào bố trí của bạn:

      diff --git a/docs/html-intl/intl/vi/training/material/index.jd b/docs/html-intl/intl/vi/training/material/index.jd
      index 44b74e1826fdf..eb489457e7c21 100644
      --- a/docs/html-intl/intl/vi/training/material/index.jd
      +++ b/docs/html-intl/intl/vi/training/material/index.jd
      @@ -17,7 +17,7 @@ page.metaDescription=Tìm hiểu cách áp dụng material design cho ứng dụ
       
       

      Material design là một hướng dẫn toàn diện về thiết kế trực quan, chuyển động và tương tác giữa nhiều nền tảng và thiết bị. Để sử dụng material design trong ứng dụng Androi của mình, hãy làm theo hướng dẫn -mô tả trong +mô tả trong đặc tả material design và sử dụng những thành phần và tính năng mới sẵn có trong Android 5.0 (API mức 21).

      diff --git a/docs/html-intl/intl/vi/training/material/lists-cards.jd b/docs/html-intl/intl/vi/training/material/lists-cards.jd index 7127649bda830..47a7d6f8f3b48 100644 --- a/docs/html-intl/intl/vi/training/material/lists-cards.jd +++ b/docs/html-intl/intl/vi/training/material/lists-cards.jd @@ -210,7 +210,7 @@ android.support.v7.widget.CardView} có thể có đổ bóng và góc bo tròn. Để biết thêm thông tin, hãy xem phần Duy trì Tính tương thích.

      -

      Sử dụng những thuộc tính sau để tùy chỉnh diện mạo của widget +

      Sử dụng những thuộc tính sau để tùy chỉnh diện mạo của widget {@link android.support.v7.widget.CardView}:

        diff --git a/docs/html-intl/intl/vi/training/material/shadows-clipping.jd b/docs/html-intl/intl/vi/training/material/shadows-clipping.jd index e9091f289fcb1..f4ce4025963f4 100644 --- a/docs/html-intl/intl/vi/training/material/shadows-clipping.jd +++ b/docs/html-intl/intl/vi/training/material/shadows-clipping.jd @@ -22,7 +22,7 @@ page.title=Định nghĩa Đổ bóng và Dạng xem Cắt hình tầm quan trọng tương đối của từng phần tử và tập chung sự chú ý của họ vào tác vụ hiện có.

        Độ cao của một dạng xem, được biểu diễn bằng thuộc tính Z, sẽ xác định diện mạo trực quan của -bóng đổ: dạng xem có giá trị Z cao hơn sẽ đổ bóng lớn hơn, mềm hơn. Dạng xem có giá trị Z cao hơn sẽ che khuất dạng xem +bóng đổ: dạng xem có giá trị Z cao hơn sẽ đổ bóng lớn hơn, mềm hơn. Dạng xem có giá trị Z cao hơn sẽ che khuất dạng xem có giá trị Z thấp hơn; tuy nhiên, giá trị Z của một dạng xem không ảnh hưởng tới kích cỡ của dạng xem.

        Đổ bóng được vẽ bởi dạng xem mẹ của dạng xem cao hơn, do vậy nó phụ thuộc vào tiêu chuẩn cắt dạng xem, @@ -51,7 +51,7 @@ trong không gian 3D.

        Hình 1 - Đổ bóng cho các độ cao dạng xem khác nhau.

        Để đặt độ cao của dạng xem trong một định nghĩa bố trí, hãy sử dụng thuộc tính android:elevation -. Để đặt độ cao của dạng xem trong mã của một hoạt động, hãy sử dụng phương thức +. Để đặt độ cao của dạng xem trong mã của một hoạt động, hãy sử dụng phương thức {@link android.view.View#setElevation View.setElevation()}.

        Để đặt độ dịch của dạng xem, hãy sử dụng phương thức {@link android.view.View#setTranslationZ @@ -59,7 +59,7 @@ View.setTranslationZ()}.

        Các phương thức {@link android.view.ViewPropertyAnimator#z ViewPropertyAnimator.z()} và {@link android.view.ViewPropertyAnimator#translationZ ViewPropertyAnimator.translationZ()} mới cho phép -bạn dễ dàng tạo hiệu ứng hoạt hình cho độ cao của dạng xem. Để biết thêm thông tin, hãy xem tài liệu tham khảo API cho +bạn dễ dàng tạo hiệu ứng hoạt hình cho độ cao của dạng xem. Để biết thêm thông tin, hãy xem tài liệu tham khảo API cho {@link android.view.ViewPropertyAnimator} và hướng dẫn cho nhà phát triển về Hoạt hình Thuộc tính .

        diff --git a/docs/html-intl/intl/zh-cn/about/versions/android-5.0.jd b/docs/html-intl/intl/zh-cn/about/versions/android-5.0.jd index 8e20975eb5124..81591450ec8fc 100644 --- a/docs/html-intl/intl/zh-cn/about/versions/android-5.0.jd +++ b/docs/html-intl/intl/zh-cn/about/versions/android-5.0.jd @@ -430,7 +430,7 @@ sdk.platform.apiLevel=21

        当系统检测到合适的网络时,它将连接到该网络并调用 {@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()} 回调。您可以在回调中使用 {@link android.net.Network} 对象来获取关于该网络的更多信息,或者指示通信使用选定的网络。

        低功耗蓝牙

        -

        Android 4.3 中作为重头戏引入了对低功耗蓝牙(“低功耗蓝牙”)的平台支持。在 Android 5.0 中,Android 设备现在可以用作低功耗蓝牙外围设备。应用可以使用此功能使附近的设备知道它的存在。例如,您可以构建相应的应用来允许设备用作计步器或健康检测器并与另一低功耗蓝牙设备交换其数据。

        +

        Android 4.3 中作为重头戏引入了对低功耗蓝牙(“低功耗蓝牙”)的平台支持。在 Android 5.0 中,Android 设备现在可以用作低功耗蓝牙外围设备。应用可以使用此功能使附近的设备知道它的存在。例如,您可以构建相应的应用来允许设备用作计步器或健康检测器并与另一低功耗蓝牙设备交换其数据。

        新的 {@link android.bluetooth.le} API 允许您的应用对公告进行广播,扫描响应,以及与附近的低功能蓝牙设备建立连接。要使用新的公告和扫描功能,请在您的清单中添加 {@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN} 权限。当用户从 Play 商店更新或下载您的应用时,会要求他们向您的应用授予以下权限:“蓝牙连接信息:允许应用控制蓝牙,包括向附近的蓝牙设备进行广播以及获取关于这些设备的信息。”

        要开始低功耗蓝牙公告以便其他设备可以发现您的应用,请调用 {@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()} 并传入 {@link android.bluetooth.le.AdvertiseCallback} 类的一个实施。回调对象将收到关于公告操作成功或失败的报告。

        diff --git a/docs/html-intl/intl/zh-cn/design/style/writing.jd b/docs/html-intl/intl/zh-cn/design/style/writing.jd index 7944c24c1ed20..c0c3e5408897c 100644 --- a/docs/html-intl/intl/zh-cn/design/style/writing.jd +++ b/docs/html-intl/intl/zh-cn/design/style/writing.jd @@ -174,7 +174,7 @@ page.type=设计
      • 使用缩写词。
      • 使用“您”或“你”直接与读者对话。
      • 语气应轻松自然,但要避免使用俚语。
      • - +

      避免使用令人困惑或令人厌烦的表达

      diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/about.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/about.jd index bfdb210ee0d94..382c4c729515c 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/about.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/about.jd @@ -6,7 +6,7 @@ page.image=/distribute/images/about-play.jpg @jd:body -
      +

      关于 Google Play

        diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/developer-console.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/developer-console.jd index 7d0bd55ca3071..d9255662f762a 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/developer-console.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/developer-console.jd @@ -4,8 +4,8 @@ page.image=/distribute/images/developer-console.jpg Xnonavpage=true @jd:body - -
        + +

        发布功能

          diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/families/faq.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/families/faq.jd index ea8bb613cda3d..7b0cf1db1e2f7 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/families/faq.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/families/faq.jd @@ -10,7 +10,7 @@ page.metaDescription=“为家庭设计”计划的问答 font-weight:bold; } - +

            本文内容

            @@ -141,7 +141,7 @@ page.metaDescription=“为家庭设计”计划的问答 假设您的应用符合该计划的所有要求,我们预计发布时间不会超过正常时间;但是,如果在“为家庭设计”审查时被拒绝,则应用的发布可能会延迟。 - +
            diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/families/start.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/families/start.jd index aab4b5aaa95b1..e81bac5843fed 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/families/start.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/families/start.jd @@ -78,7 +78,7 @@ ESRB 10+ 分级的应用只能选择一个目标年龄:9-12 岁或一般受众

            注意:在“为家庭设计”计划中发布的应用也可供 - Google Play 上的所有用户使用。 + Google Play 上的所有用户使用。

            diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/guide.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/guide.jd index b70bcb5c79eea..7b280cf1baea5 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/guide.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/guide.jd @@ -18,7 +18,7 @@ page.image=distribute/images/play_dev_guide.png

            • 在 Google Play 上发布 —使用 Google Play - 的开发者控制台,将您的应用分发给全球超过 10 亿 + 的开发者控制台,将您的应用分发给全球超过 10 亿 Android 用户。
            • diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/auto.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/auto.jd index a590446f4dfb5..9f61a35a01138 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/auto.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/auto.jd @@ -162,7 +162,7 @@ page.image=/distribute/images/gp-auto-quality.png - 布局 + 布局 diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/core.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/core.jd index 0dae9e170e583..793d110e6f87c 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/core.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/core.jd @@ -12,7 +12,7 @@ page.image=/distribute/images/core-quality-guidelines.jpg
            • Google Play
          - +

          测试

          1. 设置测试环境
          2. @@ -24,7 +24,7 @@ page.image=/distribute/images/core-quality-guidelines.jpg
          3. 平板电脑应用的质量
          4. 优化您的应用
          - +
        @@ -84,7 +84,7 @@ page.image=/distribute/images/core-quality-guidelines.jpg ID - + 说明 @@ -746,7 +746,7 @@ data-cardsizes="6x3" data-maxresults="6">
      1. 应用商品详情包括高品质的置顶大图。
      2. -
      3. 置顶大图不能包含设备图片、屏幕截图,也不能包含缩小后以及在应用适配的最小尺寸屏幕上显示时难以辨认的小文字。 +
      4. 置顶大图不能包含设备图片、屏幕截图,也不能包含缩小后以及在应用适配的最小尺寸屏幕上显示时难以辨认的小文字。
      5. @@ -1049,7 +1049,7 @@ data-cardsizes="6x3,6x3,6x3,6x3,6x3,6x3" data-maxresults="6">

        要强制启动硬件加速(在设备支持的情况下),请将 - hardware-accelerated="true"添加到应用清单文件中的<application>并重新编译。 + hardware-accelerated="true"添加到应用清单文件中的<application>并重新编译。

        diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/tablets.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/tablets.jd index 1d9d620fca356..3df311aa76125 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/tablets.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/tablets.jd @@ -48,7 +48,7 @@ Xnonavpage=true

        - 本文档中提供了相关资源的链接,这些资源可帮助您了解文中给出的各条建议。 + 本文档中提供了相关资源的链接,这些资源可帮助您了解文中给出的各条建议。

        @@ -56,7 +56,7 @@ Xnonavpage=true

        为了打造上佳的平板电脑应用体验,首先要根据应用适配的所有设备和机型,确保您的应用满足相应的应用核心质量标准。 -有关完整信息,请参阅应用核心质量准则。 +有关完整信息,请参阅应用核心质量准则

        @@ -116,7 +116,7 @@ style="font-weight:500;">舍弃拉伸变形的界面:在平板电脑上,单

          -
        • 根据需要,针对 large 和 +
        • 根据需要,针对 largexlarge 屏幕提供自定义布局。您还可以提供可根据屏幕的最短尺寸最小可用宽度和高度加载的布局。 @@ -207,8 +207,8 @@ style="font-weight:500;">复合视图将手机界面的多个单一视图( android.app.Fragment} 子类实现各个内容面板。这样一来,您可以在共用内容的不同机型和不同屏幕间最大程度地重复使用代码。
        • -
        • 确定要在哪些屏幕尺寸上使用多窗格界面,然后在相应的屏幕尺寸单元(例如 -large/xlarge)中提供不同的布局,或最小屏幕宽度(例如 +
        • 确定要在哪些屏幕尺寸上使用多窗格界面,然后在相应的屏幕尺寸单元(例如 +large/xlarge)中提供不同的布局,或最小屏幕宽度(例如 sw600dp/sw720)。
        @@ -309,7 +309,7 @@ android.app.Fragment} 子类实现各个内容面板。这样一来,您可以 data-cardSizes="9x3" data-maxResults="6">
        -

        5. +

        5. 调整字体大小和触控目标

        要确保您的应用在平板电脑上易于使用,请花些时间针对您要适配的各种屏幕配置调整平板电脑界面中的字体大小和触控目标。 @@ -345,7 +345,7 @@ android.app.Fragment} 子类实现各个内容面板。这样一来,您可以

        6. 调整主屏幕小部件的尺寸

        -

        如果您的应用中包含主屏幕小部件,需要注意以下几点,以确保用户在平板电脑屏幕上获得良好体验: +

        如果您的应用中包含主屏幕小部件,需要注意以下几点,以确保用户在平板电脑屏幕上获得良好体验:

          @@ -411,7 +411,7 @@ android.app.Fragment} 子类实现各个内容面板。这样一来,您可以 为确保分发到尽可能多的平板电脑,务必让应用适配各种支持平板电脑的 Android 版本。 对平板电脑的支持是从 Android 3.0(API 级别 11)开始的。 - 对平板电脑、手机及其他设备的统一界面框架支持是从 Android + 对平板电脑、手机及其他设备的统一界面框架支持是从 Android 4.0 开始的

          @@ -494,8 +494,8 @@ android.app.Fragment} 子类实现各个内容面板。这样一来,您可以
        • 与此类似,还请检查清单文件,找出 表明硬件功能要求不适用于平板电脑的 <permission> 元素。 -如果您找到这样的权限,请务必为功能明确声明对应的 -<uses-feature> 元素并加入 +如果您找到这样的权限,请务必为功能明确声明对应的 +<uses-feature> 元素并加入 android:required=”false” 属性。
        @@ -529,21 +529,21 @@ android.app.Fragment} 子类实现各个内容面板。这样一来,您可以

          -
        • 如果声明 +
        • 如果声明 <supports-screens> 元素,就不要指定 android:largeScreens="false"android:xlargeScreens="false"
        • -
        • 如果应用适配的 minSdkVersion 值小于 13,必须使用 +
        • 如果应用适配的 minSdkVersion 值小于 13,必须使用 android:largeScreens="true"android:xlargeScreens="true" 声明 <supports-screens> 元素。
        -

        如果应用在清单文件中声明了 +

        如果应用在清单文件中声明了 <compatible-screens> 元素,该元素应包含相关属性, 以列举应用支持的平板电脑屏幕的所有尺寸和密度组合。 -请注意,如果可能,您应避免在应用中使用 +请注意,如果可能,您应避免在应用中使用 <compatible-screens> 元素。

        @@ -586,7 +586,7 @@ android.app.Fragment} 子类实现各个内容面板。这样一来,您可以
      6. 添加在 7 英寸和 10 英寸平板电脑上截取的屏幕截图。
      7. -
      8. 如果可能,添加横屏和竖屏截取的屏幕截图。 +
      9. 如果可能,添加横屏和竖屏截取的屏幕截图。
      10. diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/tv.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/tv.jd index 6a609457bc582..99a12d585b7e8 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/tv.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/tv.jd @@ -133,7 +133,7 @@ page.image=/distribute/images/gp-tv-quality.png - 布局 + 布局 diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/wear.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/wear.jd index 99483eccc7608..eb9166de7b04e 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/wear.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/quality/wear.jd @@ -91,7 +91,7 @@ page.image=/distribute/images/gp-wear-quality.png

        手持类应用包括具有可穿戴设备特有功能的通知或直接在穿戴设备上运行的可穿戴类应用。 - + (了解方法

        @@ -441,7 +441,7 @@ data-sortorder="-timestamp" data-cardsizes="6x2" data-maxresults="6">

        - 如果我的应用不符合穿戴设备的要求,是否仍会在 Google Play + 如果我的应用不符合穿戴设备的要求,是否仍会在 Google Play 上向手机和平板电脑显示我的新应用或更新版本并且仍可在可穿戴设备上安装?

        diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/tv.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/tv.jd index e557024186a95..a1b2f4c22a16a 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/tv.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/tv.jd @@ -88,7 +88,7 @@ Android TV 的 Google Play 体验仅展示可在电视上使用的应用

        在考虑您的电视应用时,请查看开发者文档和可用性准则,并且尽可能支持这些准则。 -确保为用户设计一种出色 Leanback 观看体验,并使用 SDK 中随附的 +确保为用户设计一种出色 Leanback 观看体验,并使用 SDK 中随附的 Leanback 库来打造这种体验。您想针对电视用例优化应用的其他部分,最好在开发过程的早期确定这些部分。 @@ -261,7 +261,7 @@ Google Play 将展示优质应用,以便用户能够在 Google Play 中轻松 当您进行必要的调整后,就可以将应用的新版本上传到开发者控制台。 - +

        @@ -282,7 +282,7 @@ Google Play 将展示优质应用,以便用户能够在 Google Play 中轻松

      11. 已批准 — 您的应用已被审查并获得批准。该应用将直接提供给 Android TV 用户。 - +
      12. diff --git a/docs/html-intl/intl/zh-cn/distribute/googleplay/wear.jd b/docs/html-intl/intl/zh-cn/distribute/googleplay/wear.jd index 182abdf81d1f3..480ce5db33a9f 100644 --- a/docs/html-intl/intl/zh-cn/distribute/googleplay/wear.jd +++ b/docs/html-intl/intl/zh-cn/distribute/googleplay/wear.jd @@ -60,7 +60,7 @@ page.metaDescription=将您的应用、游戏和内容分发到 Android Wear。

        为了做好准备,以便在 Android Wear 上成功推出应用,首先要查阅在穿戴设备上提供出色应用体验的准则。 -请参考 Android +请参考 Android Wear 设计准则,了解有关针对穿戴设备扩展应用的建议,以及有关设计和可用性的详情。

        @@ -120,7 +120,7 @@ Wear 设计准则,了解有关针对穿戴设备扩展应用的建议,

        您的穿戴设备应用应表现出色,在 Android Wear 上看起来引人入胜,并且提供尽可能最佳的用户体验。 Google Play 将展示精选的优质穿戴设备应用,以便用户轻松发现。 -以下说明了您如何加入平台,提交用户喜爱的 +以下说明了您如何加入平台,提交用户喜爱的 Android Wear 应用:

        diff --git a/docs/html-intl/intl/zh-cn/distribute/resources.jd b/docs/html-intl/intl/zh-cn/distribute/resources.jd index 71bd4665a23ee..4c5644c9dda2c 100644 --- a/docs/html-intl/intl/zh-cn/distribute/resources.jd +++ b/docs/html-intl/intl/zh-cn/distribute/resources.jd @@ -8,7 +8,7 @@ page.metaDescription=我们翻译了以下一些网站资源,希望能帮助 @jd:body
        -

        - 发布应用之前,请务必确保您的应用可在目标 Android 平台版本和设备屏幕尺寸上正常运行。 + 发布应用之前,请务必确保您的应用可在目标 Android 平台版本和设备屏幕尺寸上正常运行。

        @@ -400,7 +400,7 @@ Google Play 会根据该设置来筛选应用,因此您选择的内容分级
      13. 将应用发布为免费应用后,您无法再将其改成付费应用。 -不过,您仍能通过 Google Play +不过,您仍能通过 Google Play 的应用内结算服务销售应用内商品订阅

        @@ -449,9 +449,9 @@ Google Play 会根据该设置来筛选应用,因此您选择的内容分级

        如果您希望找到更多方法通过应用获利并建立与用户的互动,则应考虑使用“应用内结算”或“即时购买”。 这些服务深受用户和开发者的欢迎。 -要使用“应用内结算”或“即时购买”,您需要对应用的二进制文件进行更改,因此,您需要先完成更改并测试实现方法,然后才能创建发布版 APK。 +要使用“应用内结算”或“即时购买”,您需要对应用的二进制文件进行更改,因此,您需要先完成更改并测试实现方法,然后才能创建发布版 APK。 + -

        相关资源

        @@ -955,7 +955,7 @@ Google Play 团队会为用户提供下载、安装和付款方面的支持,
        • - 经常查看您应用的商品详情页上的评分和评论。 + 经常查看您应用的商品详情页上的评分和评论。 注意反复出现的主题,这可能表示存在错误或其他问题。

        • @@ -991,7 +991,7 @@ Google Play 团队会为用户提供下载、安装和付款方面的支持,
        • - 确认并修正您应用中出现的问题。保持公开透明并主动在商品详情页上列出已知问题是有益之举。 + 确认并修正您应用中出现的问题。保持公开透明并主动在商品详情页上列出已知问题是有益之举。

        • diff --git a/docs/html-intl/intl/zh-cn/distribute/tools/localization-checklist.jd b/docs/html-intl/intl/zh-cn/distribute/tools/localization-checklist.jd index 522b7f5e4d4d0..e37f04337fbfc 100644 --- a/docs/html-intl/intl/zh-cn/distribute/tools/localization-checklist.jd +++ b/docs/html-intl/intl/zh-cn/distribute/tools/localization-checklist.jd @@ -62,7 +62,7 @@ page.image=/distribute/images/localization-checklist.jpg 用户可以控制其 Android 设备上使用的语言和语言区域,反过来这些因素也会影响应用的显示方式。 - +

          @@ -820,7 +820,7 @@ data-sortorder="-timestamp" data-cardsizes="9x3" data-maxresults="6">

      14. - 如果您正在准备国际化营销,请务必加入本地化的 Google Play + 如果您正在准备国际化营销,请务必加入本地化的 Google Play 徽章,让用户知道您是在 Google Play 上发布应用的。您可以使用徽章生成器快速构建本地化的徽章,然后用到您的网站或营销材料中。 您还可以获得高分辨率的资源。 diff --git a/docs/html-intl/intl/zh-cn/distribute/tools/promote/linking.jd b/docs/html-intl/intl/zh-cn/distribute/tools/promote/linking.jd index c7cf7cf700b17..e9b13c02f0028 100644 --- a/docs/html-intl/intl/zh-cn/distribute/tools/promote/linking.jd +++ b/docs/html-intl/intl/zh-cn/distribute/tools/promote/linking.jd @@ -13,7 +13,7 @@ page.metaDescription=了解如何构建链接,把用户从浏览或搜索带

        -

        Google Play 提供多种链接格式,可让你按自己需要的方式将用户从 Android 应用、网页、广告、评论、文章、社交媒体帖子等链接到你的商品。

        +

        Google Play 提供多种链接格式,可让你按自己需要的方式将用户从 Android 应用、网页、广告、评论、文章、社交媒体帖子等链接到你的商品。

        这些链接格式可让你:

          diff --git a/docs/html-intl/intl/zh-cn/google/play/billing/api.jd b/docs/html-intl/intl/zh-cn/google/play/billing/api.jd index fbdbac6c28433..ba1d63760e11b 100644 --- a/docs/html-intl/intl/zh-cn/google/play/billing/api.jd +++ b/docs/html-intl/intl/zh-cn/google/play/billing/api.jd @@ -32,7 +32,7 @@ parent.link=index.html

          另请参见

          1. 销售应用内商品
          2. -
          +
      @@ -68,7 +68,7 @@ parent.link=index.html
      1. Google Play 返回的 Bundle 中包含 PendingIntent,您的应用可用它来启动购买结帐界面。
      2. 您的应用通过调用 startIntentSenderForResult 方法来启动 PendingIntent。
      3. -
      4. 当结帐流程结束后(即用户成功购买商品或取消购买),Google Play 会向您的 onActivityResult 方法发送响应 IntentonActivityResult 的结果代码中有一个代码将用于表明用户是完成了购买还是取消了购买。响应 Intent 中会包含所购商品的相关信息,其中包括 Google Play 为了唯一标识此次购买交易而生成的 purchaseToken 字符串。Intent 中还包含使用您的私人开发者密钥签署的购买签名。
      5. +
      6. 当结帐流程结束后(即用户成功购买商品或取消购买),Google Play 会向您的 onActivityResult 方法发送响应 IntentonActivityResult 的结果代码中有一个代码将用于表明用户是完成了购买还是取消了购买。响应 Intent 中会包含所购商品的相关信息,其中包括 Google Play 为了唯一标识此次购买交易而生成的 purchaseToken 字符串。Intent 中还包含使用您的私人开发者密钥签署的购买签名。
    diff --git a/docs/html-intl/intl/zh-cn/google/play/billing/billing_admin.jd b/docs/html-intl/intl/zh-cn/google/play/billing/billing_admin.jd index 989c0e7d59a2f..50e2fe3f226d5 100644 --- a/docs/html-intl/intl/zh-cn/google/play/billing/billing_admin.jd +++ b/docs/html-intl/intl/zh-cn/google/play/billing/billing_admin.jd @@ -15,7 +15,7 @@ parent.link=index.html
  • 获取相关支持
  • - +

    另请参见

    1. 应用内结算概述
    2. diff --git a/docs/html-intl/intl/zh-cn/google/play/filters.jd b/docs/html-intl/intl/zh-cn/google/play/filters.jd index 9d68faf41bdfa..87df676bfe2b4 100644 --- a/docs/html-intl/intl/zh-cn/google/play/filters.jd +++ b/docs/html-intl/intl/zh-cn/google/play/filters.jd @@ -166,7 +166,7 @@ targetSdkVersion
      设置为 4 或更大时,所有属性的默认值

      示例 2
      清单文件声明 <uses-sdk android:minSdkVersion="3" - android:targetSdkVersion="4"> 并且不包括 + android:targetSdkVersion="4">
      并且不包括 <supports-screens> 元素。 结果:Google Play 将向所有设备的用户显示该应用,除非还有其他筛选器。

      @@ -400,10 +400,10 @@ Google Play 然后根据 这样,您可以只包括每种设备配置所需的纹理,从而减小 APK 文件的大小。 -根据每个设备是否支持您的纹理压缩格式,Google Play +根据每个设备是否支持您的纹理压缩格式,Google Play 将向其提供您已声明支持该设备的 APK。

      -

      目前,只有在每个 APK 根据以下配置提供不同筛选时,Google Play +

      目前,只有在每个 APK 根据以下配置提供不同筛选时,Google Play 才允许您为同一应用发布多个 APK:

      • OpenGL 纹理压缩格式 diff --git a/docs/html-intl/intl/zh-cn/guide/components/activities.jd b/docs/html-intl/intl/zh-cn/guide/components/activities.jd index efc1fb1ba7112..0e7c4fda89a9d 100644 --- a/docs/html-intl/intl/zh-cn/guide/components/activities.jd +++ b/docs/html-intl/intl/zh-cn/guide/components/activities.jd @@ -1,5 +1,5 @@ page.title=Activity -page.tags=Activity, Intent +page.tags=Activity, Intent @jd:body
        @@ -215,7 +215,7 @@ That Cannot Change

        启动 Activity

        您可以通过调用 {@link android.app.Activity#startActivity - startActivity()},并将其传递给描述您想启动的 Activity 的 {@link android.content.Intent} + startActivity()},并将其传递给描述您想启动的 Activity 的 {@link android.content.Intent} 来启动另一个 Activity。Intent 对象会指定您想启动的具体 Activity 或描述您想执行的操作类型(系统会为您选择合适的 Activity,甚至是来自其他应用的 Activity)。 @@ -608,7 +608,7 @@ android.app.Activity#onSaveInstanceState onSaveInstanceState()}。

        系统会先调用 {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()},然后再使 Activity 变得易于销毁。系统会向该方法传递一个 -{@link android.os.Bundle},您可以在其中使用 +{@link android.os.Bundle},您可以在其中使用 {@link android.os.Bundle#putString putString()} 和 {@link android.os.Bundle#putInt putInt()} 等方法以名称-值对形式保存有关 Activity 状态的信息。然后,如果系统终止您的应用进程,并且用户返回您的 Activity,则系统会重建该 Activity,并将 diff --git a/docs/html-intl/intl/zh-cn/guide/components/bound-services.jd b/docs/html-intl/intl/zh-cn/guide/components/bound-services.jd index ed6aaf6ecbf85..fda6ba704506a 100644 --- a/docs/html-intl/intl/zh-cn/guide/components/bound-services.jd +++ b/docs/html-intl/intl/zh-cn/guide/components/bound-services.jd @@ -636,7 +636,7 @@ onStartCommand()} android.content.Context#stopService stopService()} 为止,无论其是否绑定到任何客户端。

        -

        此外,如果您的服务已启动并接受绑定,则当系统调用您的 {@link android.app.Service#onUnbind onUnbind()} 方法时,如果您想在客户端下一次绑定到服务时接收 +

        此外,如果您的服务已启动并接受绑定,则当系统调用您的 {@link android.app.Service#onUnbind onUnbind()} 方法时,如果您想在客户端下一次绑定到服务时接收 {@link android.app.Service#onRebind onRebind()} 调用(而不是接收 {@link android.app.Service#onBind onBind()} 调用),则可选择返回 diff --git a/docs/html-intl/intl/zh-cn/guide/components/fragments.jd b/docs/html-intl/intl/zh-cn/guide/components/fragments.jd index a4c2cbb824991..12a26e25863a2 100644 --- a/docs/html-intl/intl/zh-cn/guide/components/fragments.jd +++ b/docs/html-intl/intl/zh-cn/guide/components/fragments.jd @@ -36,7 +36,7 @@ parent.link=activities.html

      • {@link android.app.FragmentManager}
      • {@link android.app.FragmentTransaction}
    - +

    另请参阅

    1. 利用片段构建动态 UI
    2. @@ -362,7 +362,7 @@ findFragmentByTag()}。

      如需查看将没有 UI 的片段用作后台工作线程的示例 Activity,请参阅 {@code FragmentRetainInstance.java} 示例,该示例包括在 SDK 示例(通过 -Android SDK 管理器提供)中,以 +Android SDK 管理器提供)中,以 <sdk_root>/APIDemos/app/src/main/java/com/example/android/apis/app/FragmentRetainInstance.java 形式位于您的系统中。

      @@ -378,7 +378,7 @@ Android SDK 管理器提供)中,以
    3. 通过 {@link android.app.FragmentManager#findFragmentById findFragmentById()}(对于在 Activity 布局中提供 UI 的片段)或 {@link android.app.FragmentManager#findFragmentByTag -findFragmentByTag()}(对于提供或不提供 UI 的片段)获取 Activity 中存在的片段
    4. +findFragmentByTag()}(对于提供或不提供 UI 的片段)获取 Activity 中存在的片段
    5. 通过 {@link android.app.FragmentManager#popBackStack()}(模拟用户发出的 Back 命令)将片段从返回栈中弹出
    6. 通过 {@link @@ -785,7 +785,7 @@ android.widget.FrameLayout}),也可能会启动一个新活动(在该活

      第二个片段 {@code DetailsFragment} 显示从 {@code TitlesFragment} 的列表中选择的项目的戏剧摘要:

      - + {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details}

      从 {@code TitlesFragment} 类中重新调用,如果用户点击某个列表项,且当前布局“根本不”包括 {@code R.id.details} @@ -798,7 +798,7 @@ Activity 以显示该项目的内容。

      {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details_activity} - +

      请注意,如果配置为横向,则此 Activity 会自行完成,以便主 Activity 可以接管并沿 {@code TitlesFragment} 显示 {@code DetailsFragment}。如果用户在纵向显示时启动 diff --git a/docs/html-intl/intl/zh-cn/guide/components/fundamentals.jd b/docs/html-intl/intl/zh-cn/guide/components/fundamentals.jd index 4ff22b64acbef..faaa0a3ffb6f3 100644 --- a/docs/html-intl/intl/zh-cn/guide/components/fundamentals.jd +++ b/docs/html-intl/intl/zh-cn/guide/components/fundamentals.jd @@ -379,7 +379,7 @@ Google Play 等外部服务会读取它们,以便当用户在其设备中搜索应用时为用户提供过滤功能。

      例如,如果您的应用需要相机,并使用 Android 2.1(API 7 级)中引入的 -API,您应该像下面这样在清单文件中以要求形式声明这些信息:

      +API,您应该像下面这样在清单文件中以要求形式声明这些信息:

       <manifest ... >
      @@ -390,7 +390,7 @@ API,您应该像下面这样在清单文件中以要求形式声明这些信
       </manifest>
       
      -

      现在,没有相机且 +

      现在,没有相机且 Android 版本低于 2.1 的设备将无法从 Google Play 安装您的应用。

      不过,您也可以声明您的应用使用相机,但并不要求必须使用。 diff --git a/docs/html-intl/intl/zh-cn/guide/components/index.jd b/docs/html-intl/intl/zh-cn/guide/components/index.jd index 53e81849c550e..73c1bdf2d7b21 100644 --- a/docs/html-intl/intl/zh-cn/guide/components/index.jd +++ b/docs/html-intl/intl/zh-cn/guide/components/index.jd @@ -11,7 +11,7 @@ page.image=images/develop/app_components.png

    - +

    关键类

    1. {@link android.app.LoaderManager}
    2. {@link android.content.Loader}
    3. -
    - + +

    相关示例

    1. @@ -51,7 +51,7 @@ android.app.Fragment}。
    2. 因此,它们无需重新查询其数据。 - +

      Loader API 摘要

      在应用中使用加载器时,可能会涉及到多个类和接口。 @@ -129,7 +129,7 @@ android.content.ContentProvider} 支持的数据。您也可以实现自己的 或 {@link android.content.AsyncTaskLoader} 子类,从其他源中加载数据。

    3. 一个 {@link android.app.LoaderManager.LoaderCallbacks} -实现。您可以使用它来创建新加载器,并管理对现有加载器的引用。
    4. +实现。您可以使用它来创建新加载器,并管理对现有加载器的引用。
    5. 一种显示加载器数据的方法,如 {@link android.widget.SimpleCursorAdapter}。
    6. 使用 @@ -140,11 +140,11 @@ android.widget.SimpleCursorAdapter}。
    7. {@link android.app.LoaderManager} 可在 {@link android.app.Activity} 或 {@link android.app.Fragment} 内管理一个或多个 {@link android.content.Loader} 实例。每个 Activity 或片段只有一个 {@link -android.app.LoaderManager}。

      +android.app.LoaderManager}。

      通常,您会使用 Activity 的 {@link android.app.Activity#onCreate onCreate()} 方法或片段的 -{@link android.app.Fragment#onActivityCreated onActivityCreated()} +{@link android.app.Fragment#onActivityCreated onActivityCreated()} 方法初始化 {@link android.content.Loader}。您执行操作如下:

      @@ -157,13 +157,13 @@ getLoaderManager().initLoader(0, null, this);
      • 用于标识加载器的唯一 ID。在此示例中,ID 为 0。
      • 在构建时提供给加载器的可选参数(在此示例中为 null -)。
      • +)。
      • {@link android.app.LoaderManager.LoaderCallbacks} 实现, {@link android.app.LoaderManager} 将调用此实现来报告加载器事件。在此示例中,本地类实现 {@link android.app.LoaderManager.LoaderCallbacks} -接口,因此它会将引用 {@code this} 传递给自己。
      • +接口,因此它会将引用 {@code this} 传递给自己。

      {@link android.app.LoaderManager#initLoader initLoader()} 调用确保加载器已初始化且处于Activity状态。这可能会出现两种结果:

      @@ -362,11 +362,11 @@ public void onLoaderReset(Loader<Cursor> loader) {

      示例

      -

      以下是一个 +

      以下是一个 {@link android.app.Fragment} 完整实现示例。它展示了一个 {@link android.widget.ListView},其中包含针对联系人内容提供程序的查询结果。它使用 {@link android.content.CursorLoader} 管理提供程序的查询。

      - +

      应用如需访问用户联系人(正如此示例中所示),其清单文件必须包括权限 {@link android.Manifest.permission#READ_CONTACTS READ_CONTACTS}。

      diff --git a/docs/html-intl/intl/zh-cn/guide/components/processes-and-threads.jd b/docs/html-intl/intl/zh-cn/guide/components/processes-and-threads.jd index c88ecf4b81e81..3f7c3cfa6d90a 100644 --- a/docs/html-intl/intl/zh-cn/guide/components/processes-and-threads.jd +++ b/docs/html-intl/intl/zh-cn/guide/components/processes-and-threads.jd @@ -47,7 +47,7 @@ Linux 进程。默认情况下,同一应用的所有组件在相同的进程 <activity>}
      {@code <service>}{@code <receiver>}{@code -<provider>}—均支持 +<provider>}—均支持 {@code android:process} 属性,此属性可以指定该组件应在哪个进程运行。您可以设置此属性,使每个组件均在各自的进程中运行,或者使一些组件共享一个进程,而其他组件则不共享。 此外,您还可以设置 {@code android:process},使不同应用的组件在相同的进程中运行,但前提是这些应用共享相同的 Linux 用户 ID 并使用相同的证书进行签署。 @@ -319,7 +319,7 @@ private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } - + /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { diff --git a/docs/html-intl/intl/zh-cn/guide/components/recents.jd b/docs/html-intl/intl/zh-cn/guide/components/recents.jd index 2bf1a5bd4ff35..bc218f44d0726 100644 --- a/docs/html-intl/intl/zh-cn/guide/components/recents.jd +++ b/docs/html-intl/intl/zh-cn/guide/components/recents.jd @@ -118,7 +118,7 @@ public void createNewDocument(View view) { 如果未找到任务或者 Intent 包含 {@link android.content.Intent#FLAG_ACTIVITY_MULTIPLE_TASK} 标志,则会以该 Activity 作为其根创建新任务。如果找到的话,则会将该任务转到前台并将新 - Intent + Intent 传递给 {@link android.app.Activity#onNewIntent onNewIntent()}。新 Activity 将获得 Intent 并在概览屏幕中创建新文档,如下例所示:

      @@ -176,7 +176,7 @@ protected void onNewIntent(Intent intent) {
      该 Activity 不会为文档创建新任务。设置此值会替代 {@link android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT} 和 {@link android.content.Intent#FLAG_ACTIVITY_MULTIPLE_TASK} 标志的行为(如果在 - Intent + Intent 中设置了其中一个标志),并且概览屏幕将为应用显示单个任务,该任务将从用户上次调用的任意 Activity 开始继续执行。
      diff --git a/docs/html-intl/intl/zh-cn/guide/components/services.jd b/docs/html-intl/intl/zh-cn/guide/components/services.jd index 9a00e704fa380..c7c848b75e39a 100644 --- a/docs/html-intl/intl/zh-cn/guide/components/services.jd +++ b/docs/html-intl/intl/zh-cn/guide/components/services.jd @@ -244,7 +244,7 @@ android.content.Context#startService startService()} 方法并传递 {@link andr {@link android.app.Service#onStartCommand onStartCommand()} 方法接收此 {@link android.content.Intent}。

      -

      例如,假设某 Activity 需要将一些数据保存到在线数据库中。该 Activity 可以启动一个协同服务,并通过向 +

      例如,假设某 Activity 需要将一些数据保存到在线数据库中。该 Activity 可以启动一个协同服务,并通过向 {@link android.content.Context#startService startService()} 传递一个 Intent,为该服务提供要保存的数据。服务通过 {@link diff --git a/docs/html-intl/intl/zh-cn/guide/components/tasks-and-back-stack.jd b/docs/html-intl/intl/zh-cn/guide/components/tasks-and-back-stack.jd index 07fdf6e80a027..88aa78ebb5161 100644 --- a/docs/html-intl/intl/zh-cn/guide/components/tasks-and-back-stack.jd +++ b/docs/html-intl/intl/zh-cn/guide/components/tasks-and-back-stack.jd @@ -45,7 +45,7 @@ Android 多任务运行机制

      一个 Activity 甚至可以启动设备上其他应用中存在的 Activity。例如,如果应用想要发送电子邮件,则可将 Intent 定义为执行“发送”操作并加入一些数据,如电子邮件地址和电子邮件。 然后,系统将打开其他应用中声明自己处理此类 - Intent 的 Activity。在这种情况下, Intent + Intent 的 Activity。在这种情况下, Intent 是要发送电子邮件,因此将启动电子邮件应用的“撰写”Activity(如果多个 Activity 支持相同 Intent,则系统会让用户选择要使用的 Activity)。发送电子邮件时,Activity 将恢复,看起来好像电子邮件 Activity 是您的应用的一部分。 即使这两个 Activity 可能来自不同的应用,但是 @@ -246,7 +246,7 @@ B)。与该应用交互之后,用户再次返回主屏幕并选择最初启

    8. {@link android.content.Intent#FLAG_ACTIVITY_SINGLE_TOP}
    9. -

      在下文中,您将了解如何使用这些清单文件属性和 Intent +

      在下文中,您将了解如何使用这些清单文件属性和 Intent 标志定义 Activity 与任务的关联方式,以及 Activity 在返回栈中的行为方式。

      此外,我们还单独介绍了有关如何在概览屏幕中显示和管理任务与 Activity 的注意事项。 @@ -282,7 +282,7 @@ A 启动 Activity B,则 Activity B 可以在其清单文件中定义它应该 B 的请求(如其清单文件中所定义)。

      注:某些适用于清单文件的启动 -模式不可用作 Intent 标志,同样,某些可用作 Intent +模式不可用作 Intent 标志,同样,某些可用作 Intent 标志的启动模式无法在清单文件中定义。

      @@ -370,7 +370,7 @@ Android 浏览器的 属性和可接受的值。

      注:使用 {@code launchMode} -属性为 Activity 指定的行为可由 Intent +属性为 Activity 指定的行为可由 Intent 附带的 Activity 启动标志替代,下文将对此进行讨论。

      @@ -378,7 +378,7 @@ Android 浏览器的

      使用 Intent 标志

      启动 Activity 时,您可以通过在传递给 {@link -android.app.Activity#startActivity startActivity()} 的 Intent +android.app.Activity#startActivity startActivity()} 的 Intent 中加入相应的标志,修改 Activity 与其任务的默认关联方式。可用于修改默认行为的标志包括:

      @@ -404,7 +404,7 @@ android.app.Activity#startActivity startActivity()} 的 Intent 属性没有值。

      {@code FLAG_ACTIVITY_CLEAR_TOP} 通常与 {@code FLAG_ACTIVITY_NEW_TASK} -结合使用。一起使用时,通过这些标志,可以找到其他任务中的现有 Activity,并将其放入可从中响应 Intent +结合使用。一起使用时,通过这些标志,可以找到其他任务中的现有 Activity,并将其放入可从中响应 Intent 的位置。

      注:如果指定 Activity 的启动模式为 {@code "standard"},则该 Activity 也会从堆栈中删除,并在其位置启动一个新实例,以便处理传入的 Intent。 diff --git a/docs/html-intl/intl/zh-cn/guide/topics/manifest/manifest-intro.jd b/docs/html-intl/intl/zh-cn/guide/topics/manifest/manifest-intro.jd index c7ade4f392dbf..65b3b232df42f 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/manifest/manifest-intro.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/manifest/manifest-intro.jd @@ -34,14 +34,14 @@ Android 系统提供有关您的应用的基本信息,系统必须获得这些

    10. 描述应用的各个组件,即:构成应用的 Activity、服务、广播接收器和内容提供程序。 为实现每个组件的类命名并发布其功能(例如,它们可以处理的 -{@link android.content.Intent +{@link android.content.Intent Intent} 消息)。根据这些声明,Android 系统可以了解这组件具体是什么,以及在什么条件下可以启动它们
    11. -
    12. 确定将托管应用组件的进程
    13. +
    14. 确定将托管应用组件的进程
    15. 声明应用必须具备哪些权限才能访问 -API 中受保护的部分并与其他应用交互
    16. +API 中受保护的部分并与其他应用交互
    17. 还声明其他应用与该应用组件交互所需具备的权限
    18. @@ -66,7 +66,7 @@ API 中受保护的部分并与其他应用交互 要查看有关任何元素的详细信息,请点击该图中或其后按字母顺序排列的元素列表中相应的元素名称,或者点击任何其他地方提到的相应元素名称。 - +

      @@ -128,7 +128,7 @@ API 中受保护的部分并与其他应用交互
       

      可出现在清单文件中的所有元素按字母顺序罗列如下。 这些是仅有的合法元素;您无法添加自己的元素或属性。 - +

      @@ -158,7 +158,7 @@ API 中受保护的部分并与其他应用交互

      - +

      文件约定

      @@ -218,7 +218,7 @@ Activity (<service>)、广播接收器 (<receiver>) 以及内容提供程序 -(<provider>)。 +(<provider>)。

      如果按照您针对组件类({@link android.app.Activity}、{@link android.app.Service}、{@link android.content.BroadcastReceiver} @@ -244,7 +244,7 @@ Activity 元素的 package 属性中所指定)。 -以下赋值与上述方法相同: +以下赋值与上述方法相同:

      <manifest package="com.example.project" . . . >
      @@ -339,7 +339,7 @@ Android 系统在启动某组件之前必须了解该组件可以处理哪些 In
       

      显式命名目标组件的 Intent 将激活该组件;过滤器不起作用。但是,不按名称指定目标的 - Intent + Intent 只有在能够通过组件的一个过滤器时才可激活该组件。

      @@ -399,7 +399,7 @@ Android 系统在启动某组件之前必须了解该组件可以处理哪些 In

      权限 是一种限制,用于限制对部分代码或设备上数据的访问。 施加限制是为了保护可能被误用以致破坏或损害用户体验的关键数据和代码。 - +

      @@ -427,7 +427,7 @@ Android 定义的一些权限: 如果授予权限,则应用能够使用受保护的功能。 否则,其访问这些功能的尝试将会失败,并且不会向用户发送任何通知。 - +

      @@ -464,7 +464,7 @@ Android <uses-permission> 元素来请求。要让应用的其他组件也能够启动受保护的 Activity,就必须请求其使用权限,即便保护是由应用本身施加的亦如此。 - +

      @@ -474,7 +474,7 @@ Android <permission> 元素再次声明。 但是,仍有必要通过 -<uses-permission> 请求使用它。 +<uses-permission> 请求使用它。

      diff --git a/docs/html-intl/intl/zh-cn/guide/topics/providers/calendar-provider.jd b/docs/html-intl/intl/zh-cn/guide/topics/providers/calendar-provider.jd index 59682843897da..b34cd8bf28911 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/providers/calendar-provider.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/providers/calendar-provider.jd @@ -42,7 +42,7 @@ page.title=日历提供程序

    19. 使用 Intent 对象查看日历数据
    - +
  • 同步适配器
  • @@ -113,14 +113,14 @@ URI 的格式为 <class>.CONTENT_URI。例如,{@li

    {@link android.provider.CalendarContract.Calendars}

    - + 此表储存日历特定信息。 此表中的每一行都包含一个日历的详细信息,例如名称、颜色、同步信息等。 {@link android.provider.CalendarContract.Events} - + 此表储存事件特定信息。 此表中的每一行都包含一个事件的信息—例如事件名称、地点、开始时间、结束时间等。 @@ -132,7 +132,7 @@ URI 的格式为 <class>.CONTENT_URI。例如,{@li {@link android.provider.CalendarContract.Instances} - + 此表储存每个事件实例的开始时间和结束时间。 此表中的每一行都表示一个事件实例。 对于一次性事件,实例与事件为 1:1 @@ -141,7 +141,7 @@ URI 的格式为 <class>.CONTENT_URI。例如,{@li {@link android.provider.CalendarContract.Attendees} - + 此表储存事件参加者(来宾)信息。 每一行都表示事件的一位来宾。 它指定来宾的类型以及事件的来宾出席响应。 @@ -149,7 +149,7 @@ URI 的格式为 <class>.CONTENT_URI。例如,{@li {@link android.provider.CalendarContract.Reminders} - + 此表储存提醒/通知数据。 每一行都表示事件的一个提醒。一个事件可以有多个提醒。 每个事件的最大提醒数量在 @@ -159,7 +159,7 @@ URI 的格式为 <class>.CONTENT_URI。例如,{@li 中指定,后者由拥有给定日历的同步适配器设置。提醒以事件发生前的分钟数形式指定,其具有一个可决定用户提醒方式的方法。 - +

    Calendar Provider API 以灵活、强大为设计宗旨。提供良好的最终用户体验以及保护日历及其数据的完整性也同样重要。 @@ -229,7 +229,7 @@ android.Manifest.permission#READ_CALENDAR} 权限。文件中必须包括用于 {@link android.provider.CalendarContract.Calendars#VISIBLE} - + 表示是否选择显示该日历的布尔值。值为 0 表示不应显示与该日历关联的事件。 值为 1 @@ -240,7 +240,7 @@ android.provider.CalendarContract.Instances} 表中行的生成。 {@link android.provider.CalendarContract.CalendarColumns#SYNC_EVENTS} - + 一个布尔值,表示是否应同步日历并将其事件存储在设备上。 值为 0 表示不同步该日历,也不将其事件存储在设备上。值为 1 @@ -268,13 +268,13 @@ public static final String[] EVENT_PROJECTION = new String[] { Calendars.CALENDAR_DISPLAY_NAME, // 2 Calendars.OWNER_ACCOUNT // 3 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1; private static final int PROJECTION_DISPLAY_NAME_INDEX = 2; private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3; - +

    +帐户不会进行同步。

    在示例的下一部分,您需要构建查询。选定范围指定查询的条件。 @@ -308,38 +308,38 @@ android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL}

    // Run query
     Cursor cur = null;
     ContentResolver cr = getContentResolver();
    -Uri uri = Calendars.CONTENT_URI;   
    -String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" 
    +Uri uri = Calendars.CONTENT_URI;
    +String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND ("
                             + Calendars.ACCOUNT_TYPE + " = ?) AND ("
                             + Calendars.OWNER_ACCOUNT + " = ?))";
     String[] selectionArgs = new String[] {"sampleuser@gmail.com", "com.google",
    -        "sampleuser@gmail.com"}; 
    -// Submit the query and get a Cursor object back. 
    +        "sampleuser@gmail.com"};
    +// Submit the query and get a Cursor object back.
     cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);

    以下后续部分使用游标单步调试结果集。它使用在示例开头设置的常量来返回每个字段的值。

    - +
    // Use the cursor to step through the returned records
     while (cur.moveToNext()) {
         long calID = 0;
         String displayName = null;
         String accountName = null;
         String ownerName = null;
    -      
    +
         // Get the field values
         calID = cur.getLong(PROJECTION_ID_INDEX);
         displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
         accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
         ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
    -              
    +
         // Do something with the values...
     
        ...
     }
     
    - +

    修改日历

    如需执行日历更新,您可以通过 @@ -434,7 +434,7 @@ android.provider.CalendarContract.Events} 参考资料。

    {@link android.provider.CalendarContract.EventsColumns#DURATION} - + RFC5545 格式的事件持续时间。例如,值为 "PT1H" 表示事件应持续一小时,值为 @@ -444,39 +444,39 @@ android.provider.CalendarContract.Events} 参考资料。

    {@link android.provider.CalendarContract.EventsColumns#ALL_DAY} - + 值为 1 表示此事件占用一整天(按照本地时区的定义)。值为 0 表示它是常规事件,可在一天内的任何时间开始和结束。 - + - - + + {@link android.provider.CalendarContract.EventsColumns#RRULE} - + 事件的重复发生规则格式。例如,"FREQ=WEEKLY;COUNT=10;WKST=SU"。 您可以在此处找到更多示例。 - + - + {@link android.provider.CalendarContract.EventsColumns#RDATE} 事件的重复发生日期。 -{@link android.provider.CalendarContract.EventsColumns#RDATE} -与 {@link android.provider.CalendarContract.EventsColumns#RRULE} +{@link android.provider.CalendarContract.EventsColumns#RDATE} +与 {@link android.provider.CalendarContract.EventsColumns#RRULE} 通常联合用于定义一组聚合重复实例。 如需查看更详细的介绍,请参阅 RFC5545 规范。 - + {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY} - + 将此事件视为忙碌时间还是可调度的空闲时间。 - + {@link android.provider.CalendarContract.EventsColumns#GUESTS_CAN_MODIFY} @@ -514,11 +514,11 @@ java.util.TimeZone#getAvailableIDs()}。请注意,如果您按参加者表

    {@link android.provider.CalendarContract.Attendees} -表的每一行都表示事件的一位参加者或来宾。调用 -{@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} +表的每一行都表示事件的一位参加者或来宾。调用 +{@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} 会返回一个参加者列表,其中包含具有给定 {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} 的事件的参加者。 -此 {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} +此 {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} 必须匹配特定事件的 {@link -android.provider.BaseColumns#_ID}。

    +android.provider.BaseColumns#_ID}。

    下表列出了可写入的字段。 插入新参加者时,您必须加入除 ATTENDEE_NAME 之外的所有字段。 @@ -718,7 +718,7 @@ Uri uri = cr.insert(Attendees.CONTENT_URI, values);

    提醒表

    {@link android.provider.CalendarContract.Reminders} -表的每一行都表示事件的一个提醒。调用 +表的每一行都表示事件的一个提醒。调用 {@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} 会返回一个提醒列表,其中包含具有给定 {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} 的事件的提醒。

    @@ -727,7 +727,7 @@ Uri uri = cr.insert(Attendees.CONTENT_URI, values);

    下表列出了提醒的可写入字段。插入新提醒时,必须加入所有字段。 请注意,同步适配器指定它们在 {@link -android.provider.CalendarContract.Calendars} 表中支持的提醒类型。详情请参阅 +android.provider.CalendarContract.Calendars} 表中支持的提醒类型。详情请参阅 {@link android.provider.CalendarContract.CalendarColumns#ALLOWED_REMINDERS} 。

    @@ -780,9 +780,9 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values);

    下表列出了一些您可以执行实例查询的字段。请注意, -时区由 -{@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} -和 +时区由 +{@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} +和 {@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_INSTANCES} 定义。

    @@ -801,18 +801,18 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values); {@link android.provider.CalendarContract.Instances#END_DAY} - + 与日历时区相应的实例儒略历结束日。 - - + + {@link android.provider.CalendarContract.Instances#END_MINUTE} - + 从日历时区午夜开始计算的实例结束时间(分钟)。 - + {@link android.provider.CalendarContract.Instances#EVENT_ID} @@ -820,16 +820,16 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values); {@link android.provider.CalendarContract.Instances#START_DAY} - 与日历时区相应的实例儒略历开始日。 + 与日历时区相应的实例儒略历开始日。 {@link android.provider.CalendarContract.Instances#START_MINUTE} - + 从日历时区午夜开始计算的实例开始时间(分钟)。 - + - + @@ -853,7 +853,7 @@ public static final String[] INSTANCE_PROJECTION = new String[] { Instances.BEGIN, // 1 Instances.TITLE // 2 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_BEGIN_INDEX = 1; @@ -868,7 +868,7 @@ long startMillis = beginTime.getTimeInMillis(); Calendar endTime = Calendar.getInstance(); endTime.set(2011, 10, 24, 8, 0); long endMillis = endTime.getTimeInMillis(); - + Cursor cur = null; ContentResolver cr = getContentResolver(); @@ -883,28 +883,28 @@ ContentUris.appendId(builder, startMillis); ContentUris.appendId(builder, endMillis); // Submit the query -cur = cr.query(builder.build(), - INSTANCE_PROJECTION, - selection, - selectionArgs, +cur = cr.query(builder.build(), + INSTANCE_PROJECTION, + selection, + selectionArgs, null); - + while (cur.moveToNext()) { String title = null; long eventID = 0; - long beginVal = 0; - + long beginVal = 0; + // Get the field values eventID = cur.getLong(PROJECTION_ID_INDEX); beginVal = cur.getLong(PROJECTION_BEGIN_INDEX); title = cur.getString(PROJECTION_TITLE_INDEX); - - // Do something with the values. - Log.i(DEBUG_TAG, "Event: " + title); + + // Do something with the values. + Log.i(DEBUG_TAG, "Event: " + title); Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(beginVal); + calendar.setTimeInMillis(beginVal); DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); - Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); + Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); } } @@ -922,9 +922,9 @@ while (cur.moveToNext()) {
    {@link android.content.Intent#ACTION_VIEW VIEW}

    content://com.android.calendar/time/<ms_since_epoch>

    - 您还可以通过 + 您还可以通过 {@link android.provider.CalendarContract#CONTENT_URI CalendarContract.CONTENT_URI} 引用 URI。 -如需查看使用该 Intent 对象的示例,请参阅
    使用 Intent 对象查看日历数据。 +如需查看使用该 Intent 对象的示例,请参阅使用 Intent 对象查看日历数据。 打开日历后定位到 <ms_since_epoch> 指定的时间。 @@ -935,11 +935,11 @@ while (cur.moveToNext()) {

    content://com.android.calendar/events/<event_id>

    - - 您还可以通过 + + 您还可以通过 {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} 引用 URI。 如需查看使用该 Intent 对象的示例,请参阅使用 Intent 对象查看日历数据。 - + 查看 <event_id> 指定的事件。 @@ -952,12 +952,12 @@ while (cur.moveToNext()) { {@link android.content.Intent#ACTION_EDIT EDIT}

    content://com.android.calendar/events/<event_id>

    - - 您还可以通过 + + 您还可以通过 {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} 引用 URI。 如需查看使用该 Intent 对象的示例,请参阅使用 Intent 对象编辑事件。 - - + + 编辑 <event_id> 指定的事件。 @@ -972,11 +972,11 @@ while (cur.moveToNext()) {
    {@link android.content.Intent#ACTION_INSERT INSERT}

    content://com.android.calendar/events

    - - 您还可以通过 + + 您还可以通过 {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} 引用 URI。 如需查看使用该 Intent 对象的示例,请参阅使用 Intent 对象插入事件。 - + 创建事件。 @@ -996,7 +996,7 @@ while (cur.moveToNext()) { 事件的名称。 - + {@link android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME} 事件开始时间,以从公元纪年开始计算的毫秒数表示。 @@ -1004,25 +1004,25 @@ CalendarContract.EXTRA_EVENT_BEGIN_TIME} {@link android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME} - + 事件结束时间,以从公元纪年开始计算的毫秒数表示。 {@link android.provider.CalendarContract#EXTRA_EVENT_ALL_DAY CalendarContract.EXTRA_EVENT_ALL_DAY} - + 一个布尔值,表示事件属于全天事件。值可以是 truefalse。 {@link android.provider.CalendarContract.EventsColumns#EVENT_LOCATION Events.EVENT_LOCATION} - + 事件的地点。 {@link android.provider.CalendarContract.EventsColumns#DESCRIPTION Events.DESCRIPTION} - + 事件描述。 @@ -1039,16 +1039,16 @@ Events.DESCRIPTION} {@link android.provider.CalendarContract.EventsColumns#ACCESS_LEVEL Events.ACCESS_LEVEL} - + 事件是私人性质还是公共性质。 {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY Events.AVAILABILITY} - + 将此事件视为忙碌时间还是可调度的空闲时间。 - - + +

    下文描述如何使用这些 Intent 对象。

    @@ -1059,23 +1059,23 @@ Events.AVAILABILITY} {@link android.Manifest.permission#WRITE_CALENDAR} 权限。

    - +

    当用户运行使用此方法的应用时,应用会将其转到日历来完成事件添加操作。 {@link android.content.Intent#ACTION_INSERT INSERT} Intent 利用 extra 字段为表单预填充日历中事件的详细信息。用户随后可取消事件、根据需要编辑表单或将事件保存到日历中。

    - +

    以下是一个代码段,用于安排一个在 2012 年 1 月 19 日上午 7:30 开始、8:30 结束的事件。请注意该代码段中的以下内容:

      -
    • 它将 {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} +
    • 它将 {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} 指定为 URI。
    • - +
    • 它使用 {@link android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME} 和 {@link @@ -1083,10 +1083,10 @@ android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME} extra 字段为表单预填充事件的时间。这些时间的值必须以从公元纪年开始计算的协调世界时毫秒数表示。
    • - +
    • 它使用 {@link android.content.Intent#EXTRA_EMAIL Intent.EXTRA_EMAIL} extra 字段提供以逗号分隔的受邀者电子邮件地址列表。
    • - +
     Calendar beginTime = Calendar.getInstance();
    @@ -1158,18 +1158,18 @@ startActivity(intent);
     
     
    • 同步适配器需要通过将 {@link android.provider.CalendarContract#CALLER_IS_SYNCADAPTER} 设置为 true 来表明它是同步适配器。
    • - - + +
    • 同步适配器需要提供 {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_NAME} 和 {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_TYPE} 作为 URI 中的查询参数。
    • - +
    • 与应用或小工具相比,同步适配器拥有写入权限的列更多。 例如,应用只能修改日历的少数几种特性, 例如其名称、显示名称、能见度设置以及是否同步日历。 相比之下,同步适配器不仅可以访问这些列,还能访问许多其他列, 例如日历颜色、时区、访问级别、地点等等。不过,同步适配器受限于它指定的 -ACCOUNT_NAME 和 +ACCOUNT_NAMEACCOUNT_TYPE

    您可以利用以下 helper 方法返回供与同步适配器一起使用的 URI:

    @@ -1180,5 +1180,5 @@ android.provider.CalendarContract.SyncColumns#ACCOUNT_TYPE} 作为 URI 中的查 .appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build(); }
    -

    如需查看同步适配器的实现示例(并非仅限与日历有关的实现),请参阅 +

    如需查看同步适配器的实现示例(并非仅限与日历有关的实现),请参阅 SampleSyncAdapter。 diff --git a/docs/html-intl/intl/zh-cn/guide/topics/providers/content-provider-basics.jd b/docs/html-intl/intl/zh-cn/guide/topics/providers/content-provider-basics.jd index 4c91d3a19c96c..b1a1c5ab49c89 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/providers/content-provider-basics.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/providers/content-provider-basics.jd @@ -251,7 +251,7 @@ mCursor = getContentResolver().query(

    表 2 显示了 - {@link android.content.ContentResolver#query + {@link android.content.ContentResolver#query query(Uri,projection,selection,selectionArgs,sortOrder)} 的参数如何匹配 SQL SELECT 语句:

    @@ -717,7 +717,7 @@ if (mCursor != null) { <uses-permission android:name="android.permission.READ_USER_DICTIONARY">

    - + 安全与权限指南中详细介绍了权限对提供程序访问的影响。

    @@ -944,7 +944,7 @@ mRowsDeleted = getContentResolver().delete(

    要在“批量模式”下访问提供程序, -您可以创建 {@link android.content.ContentProviderOperation} 对象数组,然后使用 {@link android.content.ContentResolver#applyBatch ContentResolver.applyBatch()} +您可以创建 {@link android.content.ContentProviderOperation} 对象数组,然后使用 {@link android.content.ContentResolver#applyBatch ContentResolver.applyBatch()} 将其分派给内容提供程序。 您需将内容提供程序的授权传递给此方法,而不是特定内容 URI。这样可使数组中的每个 {@link android.content.ContentProviderOperation} 对象都能适用于其他表。 @@ -1191,6 +1191,6 @@ vnd.android.cursor.item/vnd.example.line2

    - + 内容 URI 部分介绍了单个行的内容 URI。

    diff --git a/docs/html-intl/intl/zh-cn/guide/topics/providers/content-provider-creating.jd b/docs/html-intl/intl/zh-cn/guide/topics/providers/content-provider-creating.jd index 6da57435f43dc..329754e1c5d80 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/providers/content-provider-creating.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/providers/content-provider-creating.jd @@ -277,7 +277,7 @@ page.title=创建内容提供程序

    - + 内容提供程序基础知识主题中描述了内容 URI 的基础知识。

    @@ -569,7 +569,7 @@ public class ExampleProvider extends ContentProvider {

    实现 query() 方法

    - + {@link android.content.ContentProvider#query(Uri, String[], String, String[], String) ContentProvider.query()} 方法必须返回 {@link android.database.Cursor} 对象。如果失败,则会引发 {@link java.lang.Exception}。 如果您使用 SQLite 数据库作为数据存储,则只需返回由 {@link android.database.sqlite.SQLiteDatabase} 类的其中一个 @@ -831,7 +831,7 @@ vnd.android.cursor.item/vnd.com.example.provider.table1

    文件的 MIME 类型

    - 如果您的提供程序提供文件,请实现 + 如果您的提供程序提供文件,请实现 {@link android.content.ContentProvider#getStreamTypes(Uri, String) getStreamTypes()}。 该方法会为您的提供程序可以为给定内容 URI 返回的文件返回一个 MIME 类型 {@link java.lang.String} 数组。您应该通过 MIME 类型过滤器参数过滤您提供的 MIME 类型,以便只返回客户端想处理的那些 MIME 类型。 diff --git a/docs/html-intl/intl/zh-cn/guide/topics/providers/document-provider.jd b/docs/html-intl/intl/zh-cn/guide/topics/providers/document-provider.jd index fd36e29636063..db5b1a4f09d02 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/providers/document-provider.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/providers/document-provider.jd @@ -177,7 +177,7 @@ URI 授权; 中,提供程序和客户端并不直接交互。客户端请求与文件交互(即读取、编辑、创建或删除文件)的权限; -

  • 交互在应用(在本示例中为照片应用)触发 Intent +
  • 交互在应用(在本示例中为照片应用)触发 Intent {@link android.content.Intent#ACTION_OPEN_DOCUMENT} 或 {@link android.content.Intent#ACTION_CREATE_DOCUMENT} 后开始。Intent 可能包括进一步细化条件的过滤器—例如,“为我提供所有 MIME 类型为‘图像’的可打开文件”;
  • @@ -460,7 +460,7 @@ DocumentsContract.deleteDocument(getContentResolver(), uri);

    您可以使用 SAF 就地编辑文本文档。以下代码段会触发 -{@link android.content.Intent#ACTION_OPEN_DOCUMENT} Intent +{@link android.content.Intent#ACTION_OPEN_DOCUMENT} Intent 并使用类别 {@link android.content.Intent#CATEGORY_OPENABLE} 以仅显示可以打开的文档。它会进一步过滤以仅显示文本文件:

    @@ -589,7 +589,7 @@ SAF
  • 一个包括 -{@code android.content.action.DOCUMENTS_PROVIDER} 操作的 Intent +{@code android.content.action.DOCUMENTS_PROVIDER} 操作的 Intent 过滤器,以便在系统搜索提供程序时让您的提供程序出现在选取器中。
  • @@ -623,7 +623,7 @@ SAF Android 4.4 及更高版本的设备。如果您想让应用支持 {@link android.content.Intent#ACTION_GET_CONTENT} 以适应运行 Android 4.3 及更低版本的设备,则应在您的清单文件中为运行 Android 4.4 -或更高版本的设备禁用 {@link android.content.Intent#ACTION_GET_CONTENT} Intent +或更高版本的设备禁用 {@link android.content.Intent#ACTION_GET_CONTENT} Intent 过滤器。应将文档提供程序和 {@link android.content.Intent#ACTION_GET_CONTENT} 视为具有互斥性。如果您同时支持这两者,您的应用将在系统选取器 @@ -631,7 +631,7 @@ UI 中出现两次,提供两种不同的方式来访问您存储的数据。这会给用户造成困惑。

    建议按照以下步骤为运行 Android 4.4 版或更高版本的设备禁用 -{@link android.content.Intent#ACTION_GET_CONTENT} Intent +{@link android.content.Intent#ACTION_GET_CONTENT} Intent 过滤器:

      @@ -643,7 +643,7 @@ UI
    1. 添加一个Activity别名,为 4.4 版(API 19 -级)或更高版本禁用 {@link android.content.Intent#ACTION_GET_CONTENT} Intent +级)或更高版本禁用 {@link android.content.Intent#ACTION_GET_CONTENT} Intent 过滤器。例如:
      diff --git a/docs/html-intl/intl/zh-cn/guide/topics/resources/providing-resources.jd b/docs/html-intl/intl/zh-cn/guide/topics/resources/providing-resources.jd
      index ea46d86152a4a..1516814ccf476 100644
      --- a/docs/html-intl/intl/zh-cn/guide/topics/resources/providing-resources.jd
      +++ b/docs/html-intl/intl/zh-cn/guide/topics/resources/providing-resources.jd
      @@ -398,7 +398,7 @@ UI。因此,使用的值应该是布局所需要的实际最小尺寸
                 
    2. 600,适用于 600x1024 mdpi 之类的屏幕(7 英寸平板电脑)。
    3. 720,适用于 720x1280 mdpi 之类的屏幕(10 英寸平板电脑)。
    4. -

      应用为多个资源目录提供不同的 +

      应用为多个资源目录提供不同的 smallestWidth 限定符值时,系统会使用最接近(但未超出)设备 smallestWidth 的值。

      此项为 API 级别 13 中新增配置。

      @@ -428,7 +428,7 @@ smallestWidth 值。

      应用为多个资源目录提供不同的此配置值时,系统会使用最接近(但未超出)设备当前屏幕宽度的值。 此处的值考虑到了屏幕装饰元素,因此如果设备显示屏的左边缘或右边缘上有一些永久性 UI -元素,考虑到这些 UI +元素,考虑到这些 UI 元素,它会使用小于实际屏幕尺寸的宽度值,这样会减少应用的可用空间。

      @@ -456,7 +456,7 @@ smallestWidth 值。

      应用为多个资源目录提供不同的此配置值时,系统会使用最接近(但未超出)设备当前屏幕高度的值。 此处的值考虑到了屏幕装饰元素,因此如果设备显示屏的上边缘或下边缘有一些永久性 UI -元素,考虑到这些 UI +元素,考虑到这些 UI 元素,同时为减少应用的可用空间,它会使用小于实际屏幕尺寸的高度值。 非固定的屏幕装饰元素(例如,全屏时可隐藏的手机状态栏)并不在考虑范围内,标题栏或操作栏等窗口装饰也不在考虑范围内,因此应用必须准备好处理稍小于其所指定值的空间。 @@ -510,7 +510,7 @@ xlarge} 限定符标记,但设备是标准尺寸的屏幕)。

      此项为 API 级别 4 中新增配置。

      - +

      如需了解详细信息,请参阅支持多个屏幕

      另请参阅 {@link android.content.res.Configuration#screenLayout} 配置字段,该字段表示屏幕是小尺寸、标准尺寸还是大尺寸。 diff --git a/docs/html-intl/intl/zh-cn/guide/topics/ui/controls.jd b/docs/html-intl/intl/zh-cn/guide/topics/ui/controls.jd index 0f1a543d1f66d..3d78bdc57259e 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/ui/controls.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/ui/controls.jd @@ -69,7 +69,7 @@ parent.link=index.html 单选按钮 与复选框类似,不同的是只能选择组中的一个选项。 - {@link android.widget.RadioGroup RadioGroup} + {@link android.widget.RadioGroup RadioGroup}
      {@link android.widget.RadioButton RadioButton} diff --git a/docs/html-intl/intl/zh-cn/guide/topics/ui/dialogs.jd b/docs/html-intl/intl/zh-cn/guide/topics/ui/dialogs.jd index 84922b40e4454..595407d87d25f 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/ui/dialogs.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/ui/dialogs.jd @@ -32,7 +32,7 @@ page.tags=提醒对话框,对话框片段

    5. {@link android.app.DialogFragment}
    6. {@link android.app.AlertDialog}
    - +

    另请参阅

    1. 对话框设计指南
    2. @@ -248,7 +248,7 @@ AlertDialog dialog = builder.create();
      中性
      您应该在用户可能不想继续执行操作,但也不一定想要取消操作时使用此按钮。 它出现在肯定按钮和否定按钮之间。 -例如,实际操作可能是“稍后提醒我”。
      +例如,实际操作可能是“稍后提醒我”。

      对于每种按钮类型,您只能为 {@link @@ -317,10 +317,10 @@ android.app.AlertDialog.Builder#setAdapter setAdapter()} 指定一个列表。

      添加永久性多选列表或单选列表

      -

      要想添加多选项(复选框)或单选项(单选按钮)列表,请分别使用 +

      要想添加多选项(复选框)或单选项(单选按钮)列表,请分别使用 {@link android.app.AlertDialog.Builder#setMultiChoiceItems(Cursor,String,String, -DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} 或 -{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} 或 +{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()} 方法。

      @@ -346,7 +346,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { // If the user checked the item, add it to the selected items mSelectedItems.add(which); } else if (mSelectedItems.contains(which)) { - // Else, if the item is already in the array, remove it + // Else, if the item is already in the array, remove it mSelectedItems.remove(Integer.valueOf(which)); } } @@ -373,7 +373,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {

      尽管传统列表和具有单选按钮的列表都能提供“单选”操作,但如果您想持久保存用户的选择,则应使用 {@link -android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()}。也就是说,如果稍后再次打开对话框时系统应指示用户的当前选择,那么您就需要创建一个具有单选按钮的列表。

      @@ -442,7 +442,7 @@ android.app.AlertDialog.Builder#setView setView()} 将其添加到 {@link androi {@code "sans-serif"},以便两个文本字段都使用匹配的字体样式。

      要扩展 {@link android.support.v4.app.DialogFragment} -中的布局,请通过 {@link android.app.Activity#getLayoutInflater()} +中的布局,请通过 {@link android.app.Activity#getLayoutInflater()} 获取一个 {@link android.view.LayoutInflater} 并调用 {@link android.view.LayoutInflater#inflate inflate()},其中第一个参数是布局资源 ID,第二个参数是布局的父视图。然后,您可以调用 @@ -470,7 +470,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { public void onClick(DialogInterface dialog, int id) { LoginDialogFragment.this.getDialog().cancel(); } - }); + }); return builder.create(); } @@ -505,7 +505,7 @@ API。

       public class NoticeDialogFragment extends DialogFragment {
      -    
      +
           /* The activity that creates an instance of this dialog fragment must
            * implement this interface in order to receive event callbacks.
            * Each method passes the DialogFragment in case the host needs to query it. */
      @@ -513,10 +513,10 @@ public class NoticeDialogFragment extends DialogFragment {
               public void onDialogPositiveClick(DialogFragment dialog);
               public void onDialogNegativeClick(DialogFragment dialog);
           }
      -    
      +
           // Use this instance of the interface to deliver action events
           NoticeDialogListener mListener;
      -    
      +
           // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
           @Override
           public void onAttach(Activity activity) {
      @@ -543,7 +543,7 @@ public class NoticeDialogFragment extends DialogFragment {
       public class MainActivity extends FragmentActivity
                                 implements NoticeDialogFragment.NoticeDialogListener{
           ...
      -    
      +
           public void showNoticeDialog() {
               // Create an instance of the dialog fragment and show it
               DialogFragment dialog = new NoticeDialogFragment();
      @@ -656,7 +656,7 @@ public class CustomDialogFragment extends DialogFragment {
               // Inflate the layout to use as dialog or embedded fragment
               return inflater.inflate(R.layout.purchase_items, container, false);
           }
      -  
      +
           /** The system calls this only when creating the layout in a dialog. */
           @Override
           public Dialog onCreateDialog(Bundle savedInstanceState) {
      @@ -678,7 +678,7 @@ UI:

      public void showDialog() { FragmentManager fragmentManager = getSupportFragmentManager(); CustomDialogFragment newFragment = new CustomDialogFragment(); - + if (mIsLargeLayout) { // The device is using a large layout, so show the fragment as a dialog newFragment.show(fragmentManager, "dialog"); diff --git a/docs/html-intl/intl/zh-cn/guide/topics/ui/menus.jd b/docs/html-intl/intl/zh-cn/guide/topics/ui/menus.jd index b77f3bf497daa..bafbc65e7167a 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/ui/menus.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/ui/menus.jd @@ -83,9 +83,9 @@ Android 3.0 及更高版本的系统中,创建选项菜单部分。

      - +
      上下文菜单和上下文操作模式
      - +
      上下文菜单是用户长按某一元素时出现的浮动菜单。 它提供的操作将影响所选内容或上下文框架。 @@ -94,7 +94,7 @@ Android 3.0 及更高版本的系统中,创建上下文菜单部分。

      - +
      弹出菜单
      弹出菜单将以垂直列表形式显示一系列项目,这些项目将锚定到调用该菜单的视图中。 它特别适用于提供与特定内容相关的大量操作,或者为命令的另一部分提供选项。 @@ -135,7 +135,7 @@ XML 菜单资源<item>
      创建 {@link android.view.MenuItem},此元素表示菜单中的一项,可能包含嵌套的 <menu> 元素,以便创建子菜单。
      - +
      <group>
      {@code <item>} 元素的不可见容器(可选)。它支持您对菜单项进行分类,使其共享活动状态和可见性等属性。 如需了解详细信息,请参阅创建菜单组部分。 @@ -742,8 +742,8 @@ android.view.Menu} 对象中。在 API 级别 14 及更高版本中,您可以
       <ImageButton
      -    android:layout_width="wrap_content" 
      -    android:layout_height="wrap_content" 
      +    android:layout_width="wrap_content"
      +    android:layout_height="wrap_content"
           android:src="@drawable/ic_overflow_holo_dark"
           android:contentDescription="@string/descr_overflow_button"
           android:onClick="showPopup" />
      diff --git a/docs/html-intl/intl/zh-cn/guide/topics/ui/notifiers/notifications.jd b/docs/html-intl/intl/zh-cn/guide/topics/ui/notifiers/notifications.jd
      index c0bd74cdd3ac3..890831841457e 100644
      --- a/docs/html-intl/intl/zh-cn/guide/topics/ui/notifiers/notifications.jd
      +++ b/docs/html-intl/intl/zh-cn/guide/topics/ui/notifiers/notifications.jd
      @@ -321,7 +321,7 @@ Android 4.1 及更高版本的系统中可用。
       
       

      - 注:此 + 注:此 Gmail 功能需要“收件箱”扩展布局,该布局是自 Android 4.1 版本起可用的扩展通知功能的一部分。

      @@ -409,7 +409,7 @@ numMessages = 0; 您要启动的 {@link android.app.Activity} 是应用的正常工作流的一部分。在这种情况下,请设置 {@link android.app.PendingIntent} 以启动全新任务并为 -{@link android.app.PendingIntent}提供返回栈,这将重现应用的正常“返回”行为。 +{@link android.app.PendingIntent}提供返回栈,这将重现应用的正常“返回”行为。

      Gmail 应用中的通知演示了这一点。点击一封电子邮件消息的通知时,您将看到消息具体内容。 触摸返回将使您从 @@ -533,7 +533,7 @@ Gmail 中撰写消息时点击了一封电子邮件的通知,则会立即转 TaskStackBuilder.editIntentAt()} 向堆栈中的 {@link android.content.Intent} 对象添加参数。有时,需要确保目标 {@link android.app.Activity} 在用户使用“返回”导航回它时会显示有意义的数据。 - +

    3. 通过调用 diff --git a/docs/html-intl/intl/zh-cn/guide/topics/ui/overview.jd b/docs/html-intl/intl/zh-cn/guide/topics/ui/overview.jd index 5097c76e40279..78f4734fde591 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/ui/overview.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/ui/overview.jd @@ -39,7 +39,7 @@ UI
       <?xml version="1.0" encoding="utf-8"?>
       <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -              android:layout_width="fill_parent" 
      +              android:layout_width="fill_parent"
                     android:layout_height="fill_parent"
                     android:orientation="vertical" >
           <TextView android:id="@+id/text"
      @@ -60,7 +60,7 @@ UI
       

      有关创建 UI 布局的完整指南,请参阅 XML 布局。 - +

      用户界面组件

      您无需使用 {@link android.view.View} 和 {@link diff --git a/docs/html-intl/intl/zh-cn/guide/topics/ui/settings.jd b/docs/html-intl/intl/zh-cn/guide/topics/ui/settings.jd index f9be97be8c2e1..71b185da2ba21 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/ui/settings.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/ui/settings.jd @@ -226,7 +226,7 @@ android.preference.ListPreference}。这两项均包括以下三个属性:

      {@code android:key}
      对于要保留数据值的首选项,必须拥有此属性。它指定系统在将此设置的值保存在 {@link -android.content.SharedPreferences} 中时所用的唯一键(字符串)。 +android.content.SharedPreferences} 中时所用的唯一键(字符串)。

      不需要此属性的仅有情形是:首选项是 {@link android.preference.PreferenceCategory} 或{@link android.preference.PreferenceScreen},或者首选项指定要调用的 {@link android.content.Intent}(使用 {@code <intent>} 元素)或要显示的 {@link android.app.Fragment}(使用 {@code @@ -285,7 +285,7 @@ android.preference.PreferenceCategory} 内。

       <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
      -    <PreferenceCategory 
      +    <PreferenceCategory
               android:title="@string/pref_sms_storage_title"
               android:key="pref_key_storage_settings">
               <CheckBoxPreference
      @@ -293,12 +293,12 @@ android.preference.PreferenceCategory} 内。

      android:summary="@string/pref_summary_auto_delete" android:title="@string/pref_title_auto_delete" android:defaultValue="false"... /> - <Preference + <Preference android:key="pref_key_sms_delete_limit" android:dependency="pref_key_auto_delete" android:summary="@string/pref_summary_delete_limit" android:title="@string/pref_title_sms_delete"... /> - <Preference + <Preference android:key="pref_key_mms_delete_limit" android:dependency="pref_key_auto_delete" android:summary="@string/pref_summary_delete_limit" @@ -588,11 +588,11 @@ XML 标头文件定义。
      2.每组设置均由
       <?xml version="1.0" encoding="utf-8"?>
       <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
      -    <header 
      +    <header
               android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentOne"
               android:title="@string/prefs_category_one"
               android:summary="@string/prefs_summ_category_one" />
      -    <header 
      +    <header
               android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentTwo"
               android:title="@string/prefs_category_two"
               android:summary="@string/prefs_summ_category_two" >
      @@ -672,15 +672,15 @@ android.preference.Preference <Preference>} 元素均会向 {@link android
       

      例如,下面就是一个用于 Android 3.0 -及更高版本系统的首选项标头 XML 文件 ({@code res/xml/preference_headers.xml}):

      +及更高版本系统的首选项标头 XML 文件 ({@code res/xml/preference_headers.xml}):

       <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
      -    <header 
      +    <header
               android:fragment="com.example.prefs.SettingsFragmentOne"
               android:title="@string/prefs_category_one"
               android:summary="@string/prefs_summ_category_one" />
      -    <header 
      +    <header
               android:fragment="com.example.prefs.SettingsFragmentTwo"
               android:title="@string/prefs_category_two"
               android:summary="@string/prefs_summ_category_two" />
      @@ -692,18 +692,18 @@ Android 3.0 版本的系统提供相同标头的首选项文件 ({@code res/xml/
       
       
       <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
      -    <Preference 
      +    <Preference
               android:title="@string/prefs_category_one"
               android:summary="@string/prefs_summ_category_one"  >
      -        <intent 
      +        <intent
                   android:targetPackage="com.example.prefs"
                   android:targetClass="com.example.prefs.SettingsActivity"
                   android:action="com.example.prefs.PREFS_ONE" />
           </Preference>
      -    <Preference 
      +    <Preference
               android:title="@string/prefs_category_two"
               android:summary="@string/prefs_summ_category_two" >
      -        <intent 
      +        <intent
                   android:targetPackage="com.example.prefs"
                   android:targetClass="com.example.prefs.SettingsActivity"
                   android:action="com.example.prefs.PREFS_TWO" />
      @@ -920,7 +920,7 @@ android.content.Intent#ACTION_MANAGE_NETWORK_USAGE} 添加 Intent 过滤器。
       </activity>
       
      -

      此 Intent +

      此 Intent 过滤器指示系统此 Activity 控制应用的数据使用情况。因此,当用户从系统的“设置”应用检查应用所使用的数据量时,可以使用“查看应用设置”按钮启动 {@link android.preference.PreferenceActivity},这样,用户就能够优化应用使用的数据量。 @@ -975,11 +975,11 @@ android.preference.DialogPreference} public class NumberPickerPreference extends DialogPreference { public NumberPickerPreference(Context context, AttributeSet attrs) { super(context, attrs); - + setDialogLayoutResource(R.layout.numberpicker_dialog); setPositiveButtonText(android.R.string.ok); setNegativeButtonText(android.R.string.cancel); - + setDialogIcon(null); } ... @@ -1194,7 +1194,7 @@ protected void onRestoreInstanceState(Parcelable state) { // Cast state to custom BaseSavedState and pass to superclass SavedState myState = (SavedState) state; super.onRestoreInstanceState(myState.getSuperState()); - + // Set this Preference's widget to reflect the restored state mNumberPicker.setValue(myState.value); } diff --git a/docs/html-intl/intl/zh-cn/guide/topics/ui/ui-events.jd b/docs/html-intl/intl/zh-cn/guide/topics/ui/ui-events.jd index f9e976302d347..faa294d0e6b45 100644 --- a/docs/html-intl/intl/zh-cn/guide/topics/ui/ui-events.jd +++ b/docs/html-intl/intl/zh-cn/guide/topics/ui/ui-events.jd @@ -181,14 +181,14 @@ dispatchKeyEvent()} 方法的分派过程。除了通过视图捕获按

      • {@link android.app.Activity#dispatchTouchEvent(MotionEvent) - Activity.dispatchTouchEvent(MotionEvent)}:此方法允许 {@link + Activity.dispatchTouchEvent(MotionEvent)}:此方法允许 {@link android.app.Activity} 在分派给窗口之前截获所有触摸事件。
      • {@link android.view.ViewGroup#onInterceptTouchEvent(MotionEvent) ViewGroup.onInterceptTouchEvent(MotionEvent)}:此方法允许 {@link android.view.ViewGroup} 监视分派给子视图的事件。
      • {@link android.view.ViewParent#requestDisallowInterceptTouchEvent(boolean) ViewParent.requestDisallowInterceptTouchEvent(boolean)}: -对父视图调用此方法表明不应使用 {@link +对父视图调用此方法表明不应使用 {@link android.view.ViewGroup#onInterceptTouchEvent(MotionEvent)} 截获触摸事件。
      @@ -199,7 +199,7 @@ dispatchKeyEvent()} 方法的分派过程。除了通过视图捕获按 但是,如果设备具有触摸功能且用户开始通过触摸界面与之交互,则不再需要突出显示项目或聚焦到特定视图对象上。 因此,有一种交互模式称为“触摸模式”。 - +

      对于支持触摸功能的设备,当用户触摸屏幕时,设备会立即进入触摸模式。 @@ -282,7 +282,7 @@ ID。例如:

      the framework will take care of measuring, laying out, and drawing the tree as appropriate.
    - +

    Note: The entire View tree is single threaded. You must always be on the UI thread when calling any method on any View. If you are doing work on other threads and want to update the state of a View diff --git a/docs/html-intl/intl/zh-cn/preview/api-overview.jd b/docs/html-intl/intl/zh-cn/preview/api-overview.jd index 495692ac2d85f..f4f889d180214 100644 --- a/docs/html-intl/intl/zh-cn/preview/api-overview.jd +++ b/docs/html-intl/intl/zh-cn/preview/api-overview.jd @@ -762,7 +762,7 @@ Android 扩展包 (AEP) 的所有扩展(EXT_texture_sRGB_decode<

    虽然我们建议您对您的应用采用 APK Signature Scheme v2,但这项新方案并非强制性的。 如果您的应用在使用 APK Signature Scheme v2 时不能正确构建,您可以停用这项新方案。 -禁用过程会导致 Android Studio 2.2 和 Android Gradle 2.2 插件仅使用传统签名方案来签署您的应用。 +禁用过程会导致 Android Studio 2.2 和 Android Gradle 2.2 插件仅使用传统签名方案来签署您的应用。 若要仅用传统方案签署,打开多层 build.gradle 文件,然后将行 v2SigningEnabled false 添加到您的版本签名配置中: @@ -970,7 +970,7 @@ API 提供了一个包含计时数据的 {@code FrameMetrics} 对象,其渲染 虚拟文件功能可以让您的 {@link android.provider.DocumentsProvider} 返回可与 {@link android.content.Intent#ACTION_VIEW}Intent 使用的文件 URI,即使它们没有直接字节码表示。 -Android N 还允许您为用户文件(虚拟或其他类)提供备用格式。 +Android N 还允许您为用户文件(虚拟或其他类)提供备用格式。

    diff --git a/docs/html-intl/intl/zh-cn/preview/features/afw.jd b/docs/html-intl/intl/zh-cn/preview/features/afw.jd index 04e680224fbeb..0d4c56268e790 100644 --- a/docs/html-intl/intl/zh-cn/preview/features/afw.jd +++ b/docs/html-intl/intl/zh-cn/preview/features/afw.jd @@ -127,7 +127,7 @@ page.keywords="android for work", "android N", "enterprise", "QR code" android.app.admin.DevicePolicyManager#setPasswordMinimumLength setPasswordMinimumLength()}。 -个人资料所有者还能通过使用由新的 DevicePolicyManager.getParentProfileInstance() 方法返回的 {@link android.app.admin.DevicePolicyManager} 实例来设置设备锁定, +个人资料所有者还能通过使用由新的 DevicePolicyManager.getParentProfileInstance() 方法返回的 {@link android.app.admin.DevicePolicyManager} 实例来设置设备锁定, 此外,个人资料所有者可以使用 {@link android.app.admin.DevicePolicyManager} 类的新 setOrganizationColor()setOrganizationName() 方法来自定义工作挑战的凭据屏幕。 @@ -286,7 +286,7 @@ page.keywords="android for work", "android N", "enterprise", "QR code"
    • - 新类 android.app.admin.SecurityLog 和它的方法 + 新类 android.app.admin.SecurityLog 和它的方法
    • @@ -539,7 +539,7 @@ Location Settings 中的一个单独的位置访问开关允许用户拒绝对

      锁定用户图标

      - 新的用户限制 (DISALLOW_SET_USER_ICON) 阻止用户更改其用户图标。 + 新的用户限制 (DISALLOW_SET_USER_ICON) 阻止用户更改其用户图标。 用户的设备所有者或个人资料所有者仍可以更改图标。 但是个人资料所有者只能更改其控制的个人资料的用户图标。 diff --git a/docs/html-intl/intl/zh-cn/preview/features/background-optimization.jd b/docs/html-intl/intl/zh-cn/preview/features/background-optimization.jd index 5392329e2a775..4ce58aa0e9333 100644 --- a/docs/html-intl/intl/zh-cn/preview/features/background-optimization.jd +++ b/docs/html-intl/intl/zh-cn/preview/features/background-optimization.jd @@ -61,7 +61,7 @@ page.image=images/cards/card-nyc_2x.jpg

      • 面向 Preview 的应用不会收到 {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION} 广播,即使它们在清单中注册接收这些广播。 -运行的应用如果使用 {@link android.content.Context#registerReceiver Context.registerReceiver()} 注册 +运行的应用如果使用 {@link android.content.Context#registerReceiver Context.registerReceiver()} 注册 {@link android.content.BroadcastReceiver},则仍可在主线程上侦听 {@code CONNECTIVITY_CHANGE}。 diff --git a/docs/html-intl/intl/zh-cn/preview/features/security-config.jd b/docs/html-intl/intl/zh-cn/preview/features/security-config.jd index ca20c44b379c3..e029a035ca06c 100644 --- a/docs/html-intl/intl/zh-cn/preview/features/security-config.jd +++ b/docs/html-intl/intl/zh-cn/preview/features/security-config.jd @@ -739,7 +739,7 @@ CA 证书的来源,可以是
        - 用于生成 PKP 的摘要算法。目前仅支持 + 用于生成 PKP 的摘要算法。目前仅支持 {@code "SHA-256"}。
        diff --git a/docs/html-intl/intl/zh-cn/preview/overview.jd b/docs/html-intl/intl/zh-cn/preview/overview.jd index 06a905ff22358..8bbd120f93934 100644 --- a/docs/html-intl/intl/zh-cn/preview/overview.jd +++ b/docs/html-intl/intl/zh-cn/preview/overview.jd @@ -117,7 +117,7 @@ page.tags="preview", "developer", "android"

        使用 Issue Tracker 向我们报告问题并提供反馈。 -与 +与 N 开发者社区中的其他开发者建立联系。

        @@ -381,7 +381,7 @@ page.tags="preview", "developer", "android"

        - Android N Developer Preview 提供预览版 API 功能 + Android N Developer Preview 提供预览版 API 功能 — 在最终的 SDK 发布之前,这些 API 都不是正式的 API。目前,最终的 SDK 计划于 2016 年第三季度发布。 这意味着一段时期内,特别是该计划的最初几周内, API 可能会出现细微变化。 diff --git a/docs/html-intl/intl/zh-cn/preview/setup-sdk.jd b/docs/html-intl/intl/zh-cn/preview/setup-sdk.jd index 872ad7c9e14ea..c629cd9c4eccd 100644 --- a/docs/html-intl/intl/zh-cn/preview/setup-sdk.jd +++ b/docs/html-intl/intl/zh-cn/preview/setup-sdk.jd @@ -55,7 +55,7 @@ page.image=images/cards/card-n-sdk_2x.png

          -
        1. 点击 Tools >Android > +
        2. 点击 Tools >Android > SDK Manager 来打开 SDK 管理器。
        3. SDK Platforms 选项卡中选中 Android N Preview 复选框。 @@ -92,7 +92,7 @@ SDK Manager 来打开 SDK 管理器。
        4. n-preview-3-docs.zip MD5:19bcfd057a1f9dd01ffbb3d8ff7b8d81
          - SHA-1:9224bd4445cd7f653c4c294d362ccb195a2101e7 + SHA-1:9224bd4445cd7f653c4c294d362ccb195a2101e7 diff --git a/docs/html-intl/intl/zh-cn/preview/support.jd b/docs/html-intl/intl/zh-cn/preview/support.jd index 9efb5b22c83c7..353a71ddd5138 100644 --- a/docs/html-intl/intl/zh-cn/preview/support.jd +++ b/docs/html-intl/intl/zh-cn/preview/support.jd @@ -223,7 +223,7 @@ WebView 团队正在寻求关于 N 中的兼容性和运行时性能的反馈,
          系统现在使用 Activity 的元数据来决定图块模式。 (之前平铺模式是由 TileService.onTileAdded() 的返回值决定。) -如需了解详细信息,请参阅可下载的 API 参考 中的 +如需了解详细信息,请参阅可下载的 API 参考 中的 TileService.META_DATA_ACTIVE_TILE
          @@ -334,7 +334,7 @@ WebView 团队正在寻求关于 N 中的兼容性和运行时性能的反馈,
            -
          • 在将一个运行 Android 6.0 或更早版本的设备更新到 N Developer Preview 时,Google 键盘不会保留首选项数据,如最近的表情符号和声音设置。 +
          • 在将一个运行 Android 6.0 或更早版本的设备更新到 N Developer Preview 时,Google 键盘不会保留首选项数据,如最近的表情符号和声音设置。
          • diff --git a/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/index.jd b/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/index.jd index dad22089fc929..e401aae783d44 100644 --- a/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/index.jd +++ b/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/index.jd @@ -55,7 +55,7 @@ android.app.Activity} 实例接收的重要生命周期回调方法以及您如

            课程

            - +
            开始Activity
            学习有关Activity生命周期、用户如何启动您的应用以及如何执行基本Activity创建操作的基础知识。 @@ -68,5 +68,5 @@ android.app.Activity} 实例接收的重要生命周期回调方法以及您如
            重新创建Activity
            学习您的Activity被销毁时的情况以及您如何能够根据需要重新构建Activity。
            -
            + diff --git a/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/pausing.jd b/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/pausing.jd index ef5b0d57a4eca..c73a9e83708d3 100644 --- a/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/pausing.jd +++ b/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/pausing.jd @@ -8,13 +8,13 @@ trainingnavtop=true
            - +

            本课程将向您展示如何

            1. 暂停Activity
            2. 继续Activity
            - +

            您还应阅读

            • Activity @@ -59,7 +59,7 @@ android.app.Activity#onPause()} 的调用时,可能意味着Activity将暂停

              暂停Activity

              - +

              当系统为您的Activity调用 {@link android.app.Activity#onPause()} 时,它从技术角度看意味着您的Activity仍然处于部分可见状态,但往往说明用户即将离开Activity并且它很快就要进入“停止”状态。 您通常应使用 diff --git a/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/recreating.jd b/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/recreating.jd index a7971d80a53ea..76afe17f1d570 100644 --- a/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/recreating.jd +++ b/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/recreating.jd @@ -8,13 +8,13 @@ trainingnavtop=true

              - +

              本课程将向您展示如何

              1. 保存Activity状态
              2. 恢复Activity状态
              - +

              您还应阅读

              • 支持不同屏幕 @@ -105,7 +105,7 @@ public void onSaveInstanceState(Bundle savedInstanceState) { // Save the user's current game state savedInstanceState.putInt(STATE_SCORE, mCurrentScore); savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel); - + // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); } @@ -138,7 +138,7 @@ onCreate()} 中恢复一些状态数据:

                @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Always call the superclass first - + // Check whether we're recreating a previously destroyed instance if (savedInstanceState != null) { // Restore value of members from saved state @@ -157,12 +157,12 @@ android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} ,而不 系统只在存在要恢复的已保存状态时调用 {@link android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} ,因此您无需检查 {@link android.os.Bundle} 是否为 null:

                - +
                 public void onRestoreInstanceState(Bundle savedInstanceState) {
                     // Always call the superclass so it can restore the view hierarchy
                     super.onRestoreInstanceState(savedInstanceState);
                -   
                +
                     // Restore state members from saved instance
                     mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
                     mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
                diff --git a/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/starting.jd b/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/starting.jd
                index cebd7484d179c..04f380d7d0db7 100644
                --- a/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/starting.jd
                +++ b/docs/html-intl/intl/zh-cn/training/basics/activity-lifecycle/starting.jd
                @@ -9,7 +9,7 @@ trainingnavtop=true
                 
                 
                - +

                本课程将向您展示如何

                1. 了解生命周期回调
                2. @@ -17,7 +17,7 @@ trainingnavtop=true
                3. 创建一个新实例
                4. 销毁Activity
                - +

                您还应阅读

                • Activity
                • @@ -83,7 +83,7 @@ Activity还可以从“暂停”和“停止”状态回到继续状态。
                - +will want to jump to a lesson or not.--> +
                监控电池电量和充电状态
                了解如何通过确定和监控当前的电池电量和充电状态的变化来相应地调整应用的更新频率。
                @@ -46,4 +46,4 @@ will want to jump to a lesson or not.-->
                根据需要操作广播接收器
                您可以在运行时切换自己在清单中声明的广播接收器,以便根据当前设备状态停用不需要的接收器。了解如何在设备未处于特定状态的情况下切换和层叠状态变化接收器和延迟操作,以便提高效率。
                -
                \ No newline at end of file + \ No newline at end of file diff --git a/docs/html-intl/intl/zh-cn/training/monitoring-device-state/manifest-receivers.jd b/docs/html-intl/intl/zh-cn/training/monitoring-device-state/manifest-receivers.jd index 07c014f10a315..ed1b6ceb0354f 100644 --- a/docs/html-intl/intl/zh-cn/training/monitoring-device-state/manifest-receivers.jd +++ b/docs/html-intl/intl/zh-cn/training/monitoring-device-state/manifest-receivers.jd @@ -9,7 +9,7 @@ previous.link=connectivity-monitoring.html @jd:body -
                +

                本教程将指导您

                @@ -23,7 +23,7 @@ previous.link=connectivity-monitoring.html
              • intent 和 intent 过滤器
              -
              +

            监控设备状态变化的最简单方法就是,为您监控的每种状态创建 {@link android.content.BroadcastReceiver} 并在应用清单中逐一进行注册。然后,您只需根据当前设备状态在每个接收器中重新安排重复提醒即可。

            @@ -31,10 +31,10 @@ previous.link=connectivity-monitoring.html

            此方法的负面影响在于,只要系统触发了这些接收器中的任何一个,相关应用就会唤醒设备,其频率可能会远远超过所需的水平。

            更好的方法是在运行时停用或启用广播接收器。这样的话,您就可以将自己在清单中声明的接收器用作被动提醒,只有在需要时才会由系统事件触发。

            - -

            切换和层叠状态变化接收器以提高效率

            - + +

            切换和层叠状态变化接收器以提高效率

            +

            您可以使用 {@link android.content.pm.PackageManager} 切换清单中定义的任意组件的启用状态(包括您要启用或停用的任意广播接收器),具体如以下片段所示:

            ComponentName receiver = new ComponentName(context, myReceiver.class);
            diff --git a/docs/html-intl/intl/zh-cn/training/multiscreen/adaptui.jd b/docs/html-intl/intl/zh-cn/training/multiscreen/adaptui.jd
            index 89908fe46ef9b..f9e32258f716b 100644
            --- a/docs/html-intl/intl/zh-cn/training/multiscreen/adaptui.jd
            +++ b/docs/html-intl/intl/zh-cn/training/multiscreen/adaptui.jd
            @@ -10,9 +10,9 @@ previous.link=screendensities.html
             
             
             
            -
            -
            - +
            +
            +

            本教程将指导您

              @@ -27,17 +27,17 @@ previous.link=screendensities.html - +

              试试看

              - +
              下载示例应用 -

              NewsReader.zip

              -
              - - -
            -
            +

            NewsReader.zip

            +
            + + +
            +

            根据您的应用当前显示的布局,用户界面流程可能会有所不同。例如,如果您的应用处于双面板模式下,点击左侧面板上的项即可直接在右侧面板上显示相关内容;如果该应用处于单面板模式下,相关内容就应以其他活动的形式在同一面板上显示。

            @@ -56,7 +56,7 @@ public class NewsReaderActivity extends FragmentActivity { setContentView(R.layout.main_layout); View articleView = findViewById(R.id.article); - mIsDualPane = articleView != null && + mIsDualPane = articleView != null && articleView.getVisibility() == View.VISIBLE; } } @@ -116,7 +116,7 @@ public void onCreate(Bundle savedInstanceState) { else { /* use list navigation (spinner) */ actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST); - SpinnerAdapter adap = new ArrayAdapter(this, + SpinnerAdapter adap = new ArrayAdapter(this, R.layout.headline_item, CATEGORIES); actionBar.setListNavigationCallbacks(adap, handler); } @@ -168,7 +168,7 @@ public class HeadlinesFragment extends ListFragment { public class HeadlinesFragment extends ListFragment { ... @Override - public void onItemClick(AdapterView<?> parent, + public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (null != mHeadlineSelectedListener) { mHeadlineSelectedListener.onHeadlineSelected(position); diff --git a/docs/html-intl/intl/zh-cn/training/multiscreen/index.jd b/docs/html-intl/intl/zh-cn/training/multiscreen/index.jd index 02c687aaaef82..5ac0d8c4ae007 100644 --- a/docs/html-intl/intl/zh-cn/training/multiscreen/index.jd +++ b/docs/html-intl/intl/zh-cn/training/multiscreen/index.jd @@ -7,10 +7,10 @@ next.link=screensizes.html @jd:body -
            -
            - -

            依存关系和前提条件

            +
            +
            + +

            依存关系和前提条件

            • Android 1.6 或更高版本(示例应用则需要 2.1 或更高版本)
            • @@ -27,17 +27,17 @@ href="{@docRoot}tools/support-library/index.html">支持库 - -

              试试看

              - -
              + +

              试试看

              + +
              下载示例应用 -

              NewsReader.zip

              -
              - -
              -
            - +

            NewsReader.zip

            +
            + +
            +
            +

            Android 支持数百种屏幕尺寸不同的设备,包括小型手机和大型电视机。因此,请务必将您的应用设计为与所有的屏幕尺寸兼容,以便让尽可能多的用户使用该应用。

            不过,与各种类型的设备兼容还远远不够。由于各种屏幕尺寸对用户互动产生的利弊有所不同,因此要真正满足用户需求并广获好评,您的应用不仅需要支持多种屏幕,还应针对各类屏幕配置的用户体验进行优化。

            @@ -48,17 +48,17 @@ href="{@docRoot}tools/support-library/index.html">支持库

            请注意:本教程和相关的示例使用了支持库,以便在 3.0 版以下的 Android 上使用 {@link android.app.Fragment} API。因此,您需要下载该库并将其添加到您的应用,才能使用本教程中涉及的所有 API。

            - -

            教程

            - -
            -
            支持各种屏幕尺寸
            -
            本教程将向您介绍如何设计可适应多种屏幕尺寸的布局(使用灵活的视图尺寸、 {@link android.widget.RelativeLayout}、屏幕尺寸和屏幕方向限定符、别名过滤器以及自动拉伸位图)。
            - -
            支持各种屏幕密度
            -
            本教程将向您介绍如何支持具有不同像素密度的屏幕(使用非密度制约像素并提供各种密度的相应位图)。
            - -
            实施自适应用户界面流程
            -
            本教程将向您介绍如何以可适应多种屏幕尺寸/屏幕密度组合的方式实施用户界面流程(运行时对当前布局的检测,根据当前布局做出响应,处理屏幕配置变化)。
            -
            + +

            教程

            + +
            +
            支持各种屏幕尺寸
            +
            本教程将向您介绍如何设计可适应多种屏幕尺寸的布局(使用灵活的视图尺寸、 {@link android.widget.RelativeLayout}、屏幕尺寸和屏幕方向限定符、别名过滤器以及自动拉伸位图)。
            + +
            支持各种屏幕密度
            +
            本教程将向您介绍如何支持具有不同像素密度的屏幕(使用非密度制约像素并提供各种密度的相应位图)。
            + +
            实施自适应用户界面流程
            +
            本教程将向您介绍如何以可适应多种屏幕尺寸/屏幕密度组合的方式实施用户界面流程(运行时对当前布局的检测,根据当前布局做出响应,处理屏幕配置变化)。
            +
            diff --git a/docs/html-intl/intl/zh-cn/training/multiscreen/screendensities.jd b/docs/html-intl/intl/zh-cn/training/multiscreen/screendensities.jd index cdb9b7fe54c6a..342ee9519bbd0 100644 --- a/docs/html-intl/intl/zh-cn/training/multiscreen/screendensities.jd +++ b/docs/html-intl/intl/zh-cn/training/multiscreen/screendensities.jd @@ -12,8 +12,8 @@ next.link=adaptui.html -
            -
            +
            +

            本教程将指导您

              @@ -29,15 +29,15 @@ next.link=adaptui.html

          试试看

          - -
          + +
          下载示例应用 -

          NewsReader.zip

          -
          - - -
          - +

          NewsReader.zip

          + + + + +

          本教程将向您介绍如何通过提供不同资源和使用独立于分辨率的测量单位来支持不同屏幕密度。

          @@ -48,8 +48,8 @@ next.link=adaptui.html

          例如,请使用 dp(而非 px)指定两个视图间的间距:

          -<Button android:layout_width="wrap_content" 
          -    android:layout_height="wrap_content" 
          +<Button android:layout_width="wrap_content"
          +    android:layout_height="wrap_content"
               android:text="@string/clickme"
               android:layout_marginTop="20dp" />
           
          @@ -57,8 +57,8 @@ next.link=adaptui.html

          请务必使用 sp 指定文字大小:

          -<TextView android:layout_width="match_parent" 
          -    android:layout_height="wrap_content" 
          +<TextView android:layout_width="match_parent"
          +    android:layout_height="wrap_content"
               android:textSize="20sp" />
           
          diff --git a/docs/html-intl/intl/zh-cn/training/multiscreen/screensizes.jd b/docs/html-intl/intl/zh-cn/training/multiscreen/screensizes.jd index 904d09790a210..2d47d1d33cf9b 100644 --- a/docs/html-intl/intl/zh-cn/training/multiscreen/screensizes.jd +++ b/docs/html-intl/intl/zh-cn/training/multiscreen/screensizes.jd @@ -10,8 +10,8 @@ next.link=screendensities.html -
          -
          +
          +

          本教程将指导您

            @@ -30,26 +30,26 @@ next.link=screendensities.html
          1. 支持多种屏幕
          2. -

            试试看

            - -
            +

            试试看

            + +
            下载示例应用 -

            NewsReader.zip

            -
            - -
            -
          +

          NewsReader.zip

          +
          + +
          +

          此教程将向您介绍如何通过以下方法支持各种尺寸的屏幕:

          -
            -
          • 确保系统可以适当地调整您布局的尺寸以便适应屏幕
          • -
          • 根据屏幕配置提供合适的用户界面布局
          • +
              +
            • 确保系统可以适当地调整您布局的尺寸以便适应屏幕
            • +
            • 根据屏幕配置提供合适的用户界面布局
            • 确保正确的布局应用到了正确的屏幕上
            • -
            • 提供可正确缩放的位图
            • -
            +
          • 提供可正确缩放的位图
          • +
          -

          使用“wrap_content”和“match_parent”

          +

          使用“wrap_content”和“match_parent”

          要确保布局的灵活性并适应各种尺寸的屏幕,您应使用 "wrap_content""match_parent" 控制某些视图组件的宽度和高度。如果您使用 "wrap_content",系统就会将视图的宽度或高度设置成所需的最小尺寸以适应视图中的内容,而 "match_parent"(在低于 API 级别 8 的级别中称为 "fill_parent")则会展开组件以匹配其父视图的尺寸。

          @@ -65,7 +65,7 @@ next.link=screendensities.html

          图 1。纵向模式(左)和横向模式(右)下的新闻阅读器示例应用。

          -

          使用相对布局

          +

          使用相对布局

          您可以使用 {@link android.widget.LinearLayout} 的嵌套实例并结合 "wrap_content""match_parent" 尺寸,以便构建相当复杂的布局。不过,您无法通过 {@link android.widget.LinearLayout} 精确控制子视图的特殊关系;系统会将 {@link android.widget.LinearLayout} 中的视图直接并排列出。如果您需要将子视图排列出各种效果而不是一条直线,通常更合适的解决方法是使用 {@link android.widget.RelativeLayout},这样您就可以根据各组件之间的特殊关系指定布局了。例如,您可以将某个子视图对齐到屏幕左侧,同时将另一个视图对齐到屏幕右侧。

          @@ -115,8 +115,8 @@ next.link=screendensities.html

          请注意,虽然组件的尺寸有所变化,但它们的空间关系仍会保留,具体由 {@link android.widget.RelativeLayout.LayoutParams} 指定。

          - -

          使用尺寸限定符

          + +

          使用尺寸限定符

          上文所述的灵活布局或相对布局可以为您带来的优势就只有这么多了。虽然这些布局可以拉伸组件内外的空间以适应各种屏幕,但它们不一定能为每种屏幕都提供最佳的用户体验。因此,您的应用不仅应实施灵活布局,还应针对各种屏幕配置提供一些备用布局。要做到这一点,您可以使用配置限定符,这样就可以在运行时根据当前的设备配置自动选择合适的资源了(例如根据各种屏幕尺寸选择不同的布局)。

          @@ -158,7 +158,7 @@ next.link=screendensities.html

          但 Android 版本低于 3.2 的设备不支持此技术,原因是这些设备无法将 sw600dp 识别为尺寸限定符,因此您仍需使用 large 限定符。这样一来,就会有一个名称为 res/layout-large/main.xml 的文件(与 res/layout-sw600dp/main.xml 一样)。您将在下一教程中了解到避免此类布局文件出现重复的技术。

          -

          使用布局别名

          +

          使用布局别名

          最小宽度限定符仅适用于 Android 3.2 及更高版本。因此,您仍需使用与较低版本兼容的概括尺寸范围(小、正常、大和特大)。例如,如果您要将用户界面设计成在手机上显示单面板,但在 7 英寸平板电脑、电视和其他较大的设备上显示多面板,请提供以下文件:

          @@ -198,11 +198,11 @@ next.link=screendensities.html

          -

          后两个文件的内容相同,但它们并未实际定义布局。它们只是将 {@code main} 设置成了 {@code main_twopanes} 的别名。由于这些文件包含 largesw600dp 选择器,因此无论 Android 版本如何,系统都会将这些文件应用到平板电脑和电视上(版本低于 3.2 的平板电脑和电视会匹配 +

          后两个文件的内容相同,但它们并未实际定义布局。它们只是将 {@code main} 设置成了 {@code main_twopanes} 的别名。由于这些文件包含 largesw600dp 选择器,因此无论 Android 版本如何,系统都会将这些文件应用到平板电脑和电视上(版本低于 3.2 的平板电脑和电视会匹配 {@code large},版本低于 3.2 的平板电脑和电视则会匹配 sw600dp)。

          -

          使用屏幕方向限定符

          +

          使用屏幕方向限定符

          某些布局会同时支持横向模式和纵向模式,但您可以通过调整优化其中大部分布局的效果。在新闻阅读器示例应用中,每种屏幕尺寸和屏幕方向下的布局行为方式如下所示:

          diff --git a/docs/html-intl/intl/zh-tw/about/versions/android-5.0.jd b/docs/html-intl/intl/zh-tw/about/versions/android-5.0.jd index 6b3637bd3c6bb..8952a359954da 100644 --- a/docs/html-intl/intl/zh-tw/about/versions/android-5.0.jd +++ b/docs/html-intl/intl/zh-tw/about/versions/android-5.0.jd @@ -428,7 +428,7 @@ sdk.platform.apiLevel=21

          當系統偵測到適用網路時,就會自動連線並叫用 {@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()} 回呼。您可以使用回呼的 {@link android.net.Network} 物件,以取得網路的額外資訊,或是將流量導向所選的網路。

          藍牙低功耗技術

          -

          Android 4.3 平台首度導入了藍牙低功耗技術 (Bluetooth LE) 支援功能,讓裝置以主機角色建立連線。在 Android 5.0 中,Android 裝置則可以扮演 Bluetooth LE「周邊裝置」的角色。應用程式可以透過這項功能,輕鬆讓附近的裝置偵測到。舉例來說,您可以打造應用程式,讓裝置化身為計步器或健康監測器,並將資料傳送給另一台 Bluetooth LE 裝置。

          +

          Android 4.3 平台首度導入了藍牙低功耗技術 (Bluetooth LE) 支援功能,讓裝置以主機角色建立連線。在 Android 5.0 中,Android 裝置則可以扮演 Bluetooth LE「周邊裝置」的角色。應用程式可以透過這項功能,輕鬆讓附近的裝置偵測到。舉例來說,您可以打造應用程式,讓裝置化身為計步器或健康監測器,並將資料傳送給另一台 Bluetooth LE 裝置。

          全新的 {@link android.bluetooth.le} API 可讓您的應用程式播送廣告、掃描回應,以及與附近的 Bluetooth LE 裝置建立連線。如要使用全新的廣告和掃描功能,請在您的資訊清單中新增 {@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN} 權限。當使用者從 Play 商店更新或下載您的應用程式時,會看到以下的權限要求提示:「藍牙連線資訊:允許應用程式控制藍牙功能,包括對附近的藍牙裝置播送資訊,或是從附近的藍牙裝置取得資訊。」

          如要開始 Bluetooth LE 廣告功能,以便其他裝置發掘您的應用程式,請呼叫 {@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()} 並傳遞 {@link android.bluetooth.le.AdvertiseCallback} 類別實作。回呼物件會收到廣告作業成功或失敗的報告。

          diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/about.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/about.jd index f63501f5a2042..5e0eec3957c5f 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/about.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/about.jd @@ -6,7 +6,7 @@ page.image=/distribute/images/about-play.jpg @jd:body -
          +

          關於 Google Play

            diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/auto.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/auto.jd index 8fe944d9a7a33..88236c1950446 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/auto.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/auto.jd @@ -160,4 +160,4 @@ page.metaDescription=將您的應用程式與內容散佈至 Android Auto。 data-query="collection:autolanding" data-cardSizes="9x6, 6x3x2" data-maxResults="6"> -
          +
          diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/developer-console.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/developer-console.jd index a0093bb729af6..b14095b9274fe 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/developer-console.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/developer-console.jd @@ -5,7 +5,7 @@ Xnonavpage=true @jd:body -
          +

          發行功能

            diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/families/about.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/families/about.jd index b362ae9bd33e2..38c2ac1370f2a 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/families/about.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/families/about.jd @@ -36,4 +36,4 @@ page.tags="families" +
          diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/families/faq.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/families/faq.jd index 6964789008945..057e58373e674 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/families/faq.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/families/faq.jd @@ -10,7 +10,7 @@ page.metaDescription=有關 Designed for Families 的問題與回答 font-weight:bold; } - +

            本文件內容

            @@ -106,7 +106,7 @@ page.metaDescription=有關 Designed for Families 的問題與回答
            - 在您選擇加入 Designed for Families 後,Google Play 會檢閱您的應用程式,以確認其是否適合家庭使用。若您的應用程式符合所有計劃需求,預計發行時間不會長於一般發行時間;但是,若在 Designed for Families 檢閱期間拒絕應用程式,則該應用程式的發行可能會出現延遲。 + 在您選擇加入 Designed for Families 後,Google Play 會檢閱您的應用程式,以確認其是否適合家庭使用。若您的應用程式符合所有計劃需求,預計發行時間不會長於一般發行時間;但是,若在 Designed for Families 檢閱期間拒絕應用程式,則該應用程式的發行可能會出現延遲。
            diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/families/start.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/families/start.jd index bf7a7259739f2..ca44a282178af 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/families/start.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/families/start.jd @@ -51,7 +51,7 @@ page.metaDescription=只需幾個簡易步驟即可加入 Designed for Families

            - 注意:Designed for Families 計劃中已發行的應用程式也可供 Google Play 上的所有使用者使用。 + 注意:Designed for Families 計劃中已發行的應用程式也可供 Google Play 上的所有使用者使用。

            @@ -67,4 +67,4 @@ page.metaDescription=只需幾個簡易步驟即可加入 Designed for Families

            \ No newline at end of file +
          \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/guide.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/guide.jd index 0165279f68984..e70eaa3e25c8f 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/guide.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/guide.jd @@ -54,4 +54,4 @@ page.image=distribute/images/play_dev_guide.png data-query="collection:play_dev_guide" data-cardSizes="9x6" data-maxResults="1"> -
          \ No newline at end of file +
          \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/auto.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/auto.jd index bf7b702e68525..d724869350a65 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/auto.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/auto.jd @@ -431,4 +431,4 @@ data-sortorder="-timestamp" data-cardsizes="9x3" data-maxresults="6">

          重要說明:由於存在這一限制,因此您不應將生產 APK 用於 Auto 支援原型設計。 -

          \ No newline at end of file +

          \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/core.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/core.jd index feabc2002fdad..3435ec2a4e19a 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/core.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/core.jd @@ -13,7 +13,7 @@ page.image=/distribute/images/core-quality-guidelines.jpg
        5. Google Play
        6. - +

          測試

          1. 設定測試環境
          2. @@ -25,7 +25,7 @@ page.image=/distribute/images/core-quality-guidelines.jpg
          3. 平板電腦應用程式品質
          4. 最佳化您的應用程式
          - +
          @@ -70,7 +70,7 @@ page.image=/distribute/images/core-quality-guidelines.jpg - + - + - + - + - + - + - +
          ID 描述 @@ -1011,4 +1011,4 @@ data-cardsizes="6x3,6x3,6x3,6x3,6x3,6x3" data-maxresults="6">

          請確保使用{@link android.os.StrictMode.ThreadPolicy.Builder#penaltyFlashScreen() penaltyFlashScreen()}針對 ThreadPolicy 啟用政策違犯的視覺通知。 -

          \ No newline at end of file +

          \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/tablets.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/tablets.jd index 3c16f9daa50ba..d584e5375095b 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/tablets.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/tablets.jd @@ -46,7 +46,7 @@ Xnonavpage=true

          1.測試基本平板電腦應用程式品質

          -

          提供平板電腦應用程式絕佳體驗的第一步,是確保其符合應用程式所針對所有裝置及尺寸規格的核心應用程式品質準則。如需完備資訊,請參閱核心應用程式品質指導方針。 +

          提供平板電腦應用程式絕佳體驗的第一步,是確保其符合應用程式所針對所有裝置及尺寸規格的核心應用程式品質準則。如需完備資訊,請參閱核心應用程式品質指導方針

          diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/wear.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/wear.jd index 47a2d916a6048..6dc85e856b5d9 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/wear.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/quality/wear.jd @@ -395,4 +395,4 @@ data-sortorder="-timestamp" data-cardsizes="6x2" data-maxresults="6">

          是。上述需求僅判斷在 Google Play 上是否將您的應用程式視為 Android Wear 應用程式,以及該應用程式是否可供 Android Wear 使用者更輕鬆地探尋。若未接受您的應用程式為 Wear 應用程式,仍會向其他裝置類型 (例如手機或平板電腦) 提供該應用程式,並且仍會安裝在穿戴式裝置上。 -

          \ No newline at end of file +

          \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/start.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/start.jd index 3364e49bbdcae..8bff67d02eb7d 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/start.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/start.jd @@ -134,4 +134,4 @@ href="https://support.google.com/googleplay/android-developer/bin/answer.py?hl=e data-query="collection:distribute/googleplay/gettingstarted" data-sortOrder="-timestamp" data-cardSizes="9x3" - data-maxResults="6"> \ No newline at end of file + data-maxResults="6"> \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/tv.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/tv.jd index c4f7a7cd089c9..aa2096ad4cdd3 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/tv.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/tv.jd @@ -173,7 +173,7 @@ page.metaDescription=將您的應用程式、遊戲與內容散佈至 Android

          5.追蹤您的檢閱與核准

          - 若您的應用程式符合 Android 電視的技術與品質準則 (如上所述),則會向 Android 電視的使用者提供您的應用程式。若您的應用程式不符合該準則,您將收到傳送至您開發人員帳戶地址的通知電子郵件,內含需要修正的領域的摘要。若您已進行所需調整,可以將新版本的應用程式上傳至 Developer Console。 + 若您的應用程式符合 Android 電視的技術與品質準則 (如上所述),則會向 Android 電視的使用者提供您的應用程式。若您的應用程式不符合該準則,您將收到傳送至您開發人員帳戶地址的通知電子郵件,內含需要修正的領域的摘要。若您已進行所需調整,可以將新版本的應用程式上傳至 Developer Console。

          @@ -190,7 +190,7 @@ page.metaDescription=將您的應用程式、遊戲與內容散佈至 Android

        7. - 已核准 - 已檢閱並核准您的應用程式。會直接向 Android 電視使用者提供該應用程式。 + 已核准 - 已檢閱並核准您的應用程式。會直接向 Android 電視使用者提供該應用程式。
        8. @@ -207,4 +207,4 @@ page.metaDescription=將您的應用程式、遊戲與內容散佈至 Android data-query="collection:tvlanding" data-cardSizes="9x6, 6x3x2" data-maxResults="6"> - \ No newline at end of file + \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/distribute/googleplay/wear.jd b/docs/html-intl/intl/zh-tw/distribute/googleplay/wear.jd index 19a48f56a5b55..f4aca5cca51ab 100644 --- a/docs/html-intl/intl/zh-tw/distribute/googleplay/wear.jd +++ b/docs/html-intl/intl/zh-tw/distribute/googleplay/wear.jd @@ -196,4 +196,4 @@ page.metaDescription=將您的應用程式、遊戲與內容散佈至 Android We data-query="collection:wearlanding" data-cardSizes="6x2" data-maxResults="3"> - \ No newline at end of file + \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/distribute/tools/launch-checklist.jd b/docs/html-intl/intl/zh-tw/distribute/tools/launch-checklist.jd index 6e974174849be..167c4f10d5ace 100644 --- a/docs/html-intl/intl/zh-tw/distribute/tools/launch-checklist.jd +++ b/docs/html-intl/intl/zh-tw/distribute/tools/launch-checklist.jd @@ -789,4 +789,4 @@ data-maxresults="6"> data-query="collection:distribute/toolsreference/launchchecklist/afterlaunch" data-sortOrder="-timestamp" data-cardSizes="9x3,9x3,9x3,9x3,9x3,9x3" - data-maxResults="6"> \ No newline at end of file + data-maxResults="6"> \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/distribute/tools/localization-checklist.jd b/docs/html-intl/intl/zh-tw/distribute/tools/localization-checklist.jd index 1b95d0b3458d1..c34fcee498bc0 100644 --- a/docs/html-intl/intl/zh-tw/distribute/tools/localization-checklist.jd +++ b/docs/html-intl/intl/zh-tw/distribute/tools/localization-checklist.jd @@ -713,4 +713,4 @@ data-maxresults="6"> data-query="collection:distribute/toolsreference/localizationchecklist/supportlaunch" data-sortOrder="-timestamp" data-cardSizes="9x3,9x3,6x3,9x3,9x3,9x3" - data-maxResults="6"> \ No newline at end of file + data-maxResults="6"> \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/google/play/filters.jd b/docs/html-intl/intl/zh-tw/google/play/filters.jd index e96b9ddcacd80..eec87ac751561 100644 --- a/docs/html-intl/intl/zh-tw/google/play/filters.jd +++ b/docs/html-intl/intl/zh-tw/google/play/filters.jd @@ -263,4 +263,4 @@ href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-featur

          注意:針對同一應用程式發行多個 APK 是進階功能,多數應用程式應僅發行為諸多裝置組態提供支援的單一 APK。發行多個 APK 需要您遵循篩選器中的特定規則,並格外注意每個 APK 的版本代碼,以確保每個組態使用正確的更新路徑。

          -

          若您需要有關如何在 Google Play 上發行多個 APK 的詳細資訊,請參閱多 APK 支援

          \ No newline at end of file +

          若您需要有關如何在 Google Play 上發行多個 APK 的詳細資訊,請參閱多 APK 支援

          \ No newline at end of file diff --git a/docs/html-intl/intl/zh-tw/guide/components/bound-services.jd b/docs/html-intl/intl/zh-tw/guide/components/bound-services.jd index da47634b894fa..e26e993fd672f 100644 --- a/docs/html-intl/intl/zh-tw/guide/components/bound-services.jd +++ b/docs/html-intl/intl/zh-tw/guide/components/bound-services.jd @@ -303,7 +303,7 @@ public class BindingActivity extends Activity { } -

          上述範例顯示:用戶端如何使用 +

          上述範例顯示:用戶端如何使用 {@link android.content.ServiceConnection} 的實作和 {@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} 回呼,繫結至服務。下一節提供關於繫結至服務處理程序的詳細資訊。

          @@ -334,7 +334,7 @@ android.os.Messenger} 讓服務一次處理一個呼叫。如果您的服務必 -

          如果服務要和遠端處理程序溝通,則可以使用 +

          如果服務要和遠端處理程序溝通,則可以使用 {@link android.os.Messenger} 為您的服務提供介面。此技術讓您不需要使用 AIDL,就可以執行處理程序間通訊 (IPC)。

          @@ -636,7 +636,7 @@ android.content.Context#stopService stopService()} 加以停止,否則服務

          -

          此外,如果您的服務已啟動並且接受繫結,當系統呼叫您的 {@link android.app.Service#onUnbind onUnbind()} 方法時,可以選擇傳回 +

          此外,如果您的服務已啟動並且接受繫結,當系統呼叫您的 {@link android.app.Service#onUnbind onUnbind()} 方法時,可以選擇傳回 {@code true} (如果您希望用戶端下次繫結至服務時,可以接收 {@link android.app.Service#onRebind onRebind()} 呼叫,而不是接收 {@link android.app.Service#onBind onBind()} 的呼叫)。{@link android.app.Service#onRebind diff --git a/docs/html-intl/intl/zh-tw/guide/components/fragments.jd b/docs/html-intl/intl/zh-tw/guide/components/fragments.jd index e54769b0c88b3..dfef8f1ffaa9e 100644 --- a/docs/html-intl/intl/zh-tw/guide/components/fragments.jd +++ b/docs/html-intl/intl/zh-tw/guide/components/fragments.jd @@ -36,7 +36,7 @@ parent.link=activities.html

        9. {@link android.app.FragmentManager}
        10. {@link android.app.FragmentTransaction}
        11. - +

          另請參閱

          1. 使用片段建置動態 UI
          2. @@ -46,7 +46,7 @@ parent.link=activities.html -

            {@link android.app.Fragment} 代表一種行為或 +

            {@link android.app.Fragment} 代表一種行為或 {@link android.app.Activity} 中的一部分使用者介面。您可以合併單一 Activity 中的多個片段,藉此建置 多窗格 UI 以及在多個 Activity 中重複使用片段。您可以將片段想成是 Activity 的模組化區段,片段擁有自己的生命週期、接收自己的輸入事件,而且您可以在 Activity 執行時新增或移除片段 (有點像是您可以在不同 Activity 中重複使用的「子 Activity」)。 @@ -204,11 +204,11 @@ android.app.ListFragment} 的子類別,則實作完畢後系統預設會傳回 {@link android.widget.ListView},因此您不必加以實作。

            如要從 {@link -android.app.Fragment#onCreateView onCreateView()} 傳回版面配置,您可以從 XML 中定義的l版面配置資源擴大它。為協助您完成這項作業,{@link android.app.Fragment#onCreateView onCreateView()} 提供了 +android.app.Fragment#onCreateView onCreateView()} 傳回版面配置,您可以從 XML 中定義的l版面配置資源擴大它。為協助您完成這項作業,{@link android.app.Fragment#onCreateView onCreateView()} 提供了 {@link android.view.LayoutInflater} 物件。

            -

            例如,以下是 {@link android.app.Fragment} 的子類別,可從 +

            例如,以下是 {@link android.app.Fragment} 的子類別,可從 {@code example_fragment.xml} 檔案載入版面配置:

            @@ -378,7 +378,7 @@ FragmentRetainInstance.java} 範例 (可透過 Android SDK Manager 存取)
               
          3. 使用 {@link android.app.FragmentManager#findFragmentById findFragmentById()} (針對在 Activity 版面配置中提供 UI 的片段) 或 {@link android.app.FragmentManager#findFragmentByTag findFragmentByTag()} (針對未提供 UI 的片段) 取得 Activity 中的現有片段。 -
          4. +
          5. 使用 {@link android.app.FragmentManager#popBackStack()} (模擬使用者的「返回」命令) 將片段從返回堆疊中推出。
          6. 使用 {@link @@ -563,7 +563,7 @@ public static class FragmentA extends ListFragment {
          7. 如果 Activity 並未實作介面,那麼片段會擲回 -{@link java.lang.ClassCastException}。成功擲回時,{@code mListener} 成員會保留 Activity 所實作 +{@link java.lang.ClassCastException}。成功擲回時,{@code mListener} 成員會保留 Activity 所實作 {@code OnArticleSelectedListener} 的參照資料,以便片段 A 呼叫 {@code OnArticleSelectedListener} 介面定義的方法與 Activity 分享事件。 例如,假設片段 A 是 @@ -739,7 +739,7 @@ android.app.Activity#onCreate onCreate()} 回呼後,Activity 中的片段就 這個 Activity 範例同時示範了如何根據螢幕設定提供不同的片段設定。

            -

            注意:如需這個 Activity 的完整原始碼,請查閱 +

            注意:如需這個 Activity 的完整原始碼,請查閱 {@code FragmentLayout.java}

            @@ -785,7 +785,7 @@ android.widget.FrameLayout}),或是啟動新的 Activity (藉此顯示片段)

            第二個片段 {@code DetailsFragment} 則會針對 {@code TitlesFragment} 中,使用者所選清單項目的劇本摘要:

            - + {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details}

            針對 {@code TitlesFragment} 類別發出的回呼,如果使用者點擊清單項目,而且目前的版面配置「並未」包含 {@code R.id.details} 檢視 ({@code DetailsFragment} 所屬的檢視),則應用程式會執行 {@code DetailsActivity} Activity 來顯示項目內容。 @@ -798,7 +798,7 @@ android.widget.FrameLayout}),或是啟動新的 Activity (藉此顯示片段) {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details_activity} - +

            請注意,這個 Activity 會在螢幕採用橫向版面配置的情況下自行結束,因此主要 Activity 會接續顯示 {@code TitlesFragment} 旁的 {@code DetailsFragment}。如果使用者在採用直向版面配置的裝置上執行 {@code DetailsActivity},然後將該裝置旋轉成橫向 (這會重新執行目前的 Activity),就可能會發生這種情況。 diff --git a/docs/html-intl/intl/zh-tw/guide/components/fundamentals.jd b/docs/html-intl/intl/zh-tw/guide/components/fundamentals.jd index d3b3c2899614a..9e4079e5e35e9 100644 --- a/docs/html-intl/intl/zh-tw/guide/components/fundamentals.jd +++ b/docs/html-intl/intl/zh-tw/guide/components/fundamentals.jd @@ -309,7 +309,7 @@ href="{@docRoot}guide/topics/manifest/provider-element.html"><provider>

            系統看不到您納入來源但未在宣示說明中宣告的 Activity、服務和內容供應程式,因此系統無法執行這些項目。 -不過,您可在宣示說明宣告廣播接收器,或是透過程式碼以動態方式建立廣播接收器 (將廣播接收器建立為 +不過,您可在宣示說明宣告廣播接收器,或是透過程式碼以動態方式建立廣播接收器 (將廣播接收器建立為 {@link android.content.BroadcastReceiver} 物件),然後呼叫 {@link android.content.Context#registerReceiver registerReceiver()} 向系統註冊廣播接收器。 @@ -379,7 +379,7 @@ startActivity()},系統就可能會啟動您的 Activity 讓使用者撰寫及

            例如,假設您的應用程式需要相機且採用 Android 2.1 (API 級別 7) 導入的 API,建議您用下列方式在宣示說明檔案中宣告這些需求: -

            +

             <manifest ... >
            diff --git a/docs/html-intl/intl/zh-tw/guide/components/index.jd b/docs/html-intl/intl/zh-tw/guide/components/index.jd
            index f34c7120e8ad3..a59bcd465cb9b 100644
            --- a/docs/html-intl/intl/zh-tw/guide/components/index.jd
            +++ b/docs/html-intl/intl/zh-tw/guide/components/index.jd
            @@ -11,7 +11,7 @@ page.image=images/develop/app_components.png
             
               
          - +

          重要類別

          1. {@link android.app.LoaderManager}
          2. {@link android.content.Loader}
          3. -
          - + +

          相關範例

          1. LoaderCursor @@ -51,7 +51,7 @@ android.app.Fragment} 。
          2. 因此不需要重新查詢資料。 - +

            載入器 API 摘要

            有多個類別和介面可能與在應用程式中使用載入器有關。 @@ -129,7 +129,7 @@ android.content.ContentProvider} 所備份資料的 {@link android.content.Curso

          3. {@link android.app.LoaderManager.LoaderCallbacks} 的實作。 您可以在這裡建立新的載入器和管理對現有載入器的參照。 -
          4. +
          5. 顯示載入器資料的一種方式,例如 {@link android.widget.SimpleCursorAdapter}。
          6. 使用 {@link android.content.CursorLoader} 時的資料來源,例如 {@link android.content.ContentProvider}。 @@ -140,7 +140,7 @@ android.widget.SimpleCursorAdapter}。
          7. {@link android.app.LoaderManager} 可在 {@link android.app.Activity} 或 {@link android.app.Fragment} 內管理一或多個 {@link android.content.Loader} 執行個體。 每個 Activity 或片段只能有一個 {@link -android.app.LoaderManager}。

            +android.app.LoaderManager}。

            您通常會在 Activity 的 {@link android.app.Activity#onCreate onCreate()} 方法內或在片段的 {@link android.app.Fragment#onActivityCreated onActivityCreated()} 方法內,初始化 {@link android.content.Loader}, @@ -157,13 +157,13 @@ getLoaderManager().initLoader(0, null, this);

            • 可識別載入器的不重複 ID。在本範例中,此 ID 為 0。
            • 可在建構時提供給載入器的選用引數 (在本範例中為null)。 -
            • +
            • {@link android.app.LoaderManager.LoaderCallbacks} 實作, {@link android.app.LoaderManager} 會呼叫此實作來回報載入器事件。在本範例中,本機類別會實作 {@link android.app.LoaderManager.LoaderCallbacks} 執行個體,以將參照傳送給它自己 ({@code this})。 -
            • +

            {@link android.app.LoaderManager#initLoader initLoader()} 呼叫可確保載入器已初始化且處於有效狀態。 可能會有兩種結果:

            @@ -343,7 +343,7 @@ public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

            這個方法是在正要重設先前建立的載入器時呼叫,以便使其資料無法使用。 此回呼方法可讓您知道即將要發佈資料,而能先行將其參照移除。  

            -

            此實作會以 null 的值呼叫 +

            此實作會以 null 的值呼叫 {@link android.widget.SimpleCursorAdapter#swapCursor swapCursor()}:

            @@ -366,7 +366,7 @@ public void onLoaderReset(Loader<Cursor> loader) { android.app.Fragment} 的完整實作, 其顯示的 {@link android.widget.ListView} 包含聯絡人內容供應程式的查詢結果。它使用 {@link android.content.CursorLoader} 管理對供應程式的查詢。

            - +

            如本範例所示,針對要存取使用者聯絡人的應用程式,它的宣示說明必須包含 {@link android.Manifest.permission#READ_CONTACTS READ_CONTACTS} 權限。

            diff --git a/docs/html-intl/intl/zh-tw/guide/components/processes-and-threads.jd b/docs/html-intl/intl/zh-tw/guide/components/processes-and-threads.jd index 74dbb8ebb3f15..56027ceb88a35 100644 --- a/docs/html-intl/intl/zh-tw/guide/components/processes-and-threads.jd +++ b/docs/html-intl/intl/zh-tw/guide/components/processes-and-threads.jd @@ -49,7 +49,7 @@ page.tags=生命週期、背景 <receiver>}
            {@code <provider>} — 的宣示說明項目都支援 {@code android:process} 屬性,這項屬性能指定元件應在哪個處理程序執行。 您可以設定此屬性讓每個元件都以自己的處理程序執行,或只讓當中的部分元件共用同一處理程序。 -您也可以設定 +您也可以設定 {@code android:process},讓不同應用程式的元件以相同的處理程序執行,只要這些應用程式分享相同的 Linux 使用者 ID 並以相同的憑證簽署。

            @@ -142,7 +142,7 @@ android.content.Context#startService startService()} 方法啟動的服務的處
          8. 背景處理程序 -

            這種處理程序會保留使用者目前看不見的 Activity (已呼叫 Activity 的 +

            這種處理程序會保留使用者目前看不見的 Activity (已呼叫 Activity 的 {@link android.app.Activity#onStop onStop()} 方法)。這些處理程序會間接影響使用者體驗,且系統能隨時將其終止,藉此回收記憶體以供前景、可見或服務處理程序使用。 @@ -319,7 +319,7 @@ private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } - + /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { diff --git a/docs/html-intl/intl/zh-tw/guide/components/recents.jd b/docs/html-intl/intl/zh-tw/guide/components/recents.jd index d56c12c0e87bb..5ac0e2625bef2 100644 --- a/docs/html-intl/intl/zh-tw/guide/components/recents.jd +++ b/docs/html-intl/intl/zh-tw/guide/components/recents.jd @@ -181,7 +181,7 @@ protected void onNewIntent(Intent intent) {

            注意:如果值不是 {@code none} 與 {@code never},則 Activity 必須使用 {@code launchMode="standard"} 定義。 -如果沒有指定此屬性,則會使用 +如果沒有指定此屬性,則會使用 {@code documentLaunchMode="none"}。

            移除工作

            diff --git a/docs/html-intl/intl/zh-tw/guide/components/tasks-and-back-stack.jd b/docs/html-intl/intl/zh-tw/guide/components/tasks-and-back-stack.jd index e23301d641bcf..e3ce58f7770de 100644 --- a/docs/html-intl/intl/zh-tw/guide/components/tasks-and-back-stack.jd +++ b/docs/html-intl/intl/zh-tw/guide/components/tasks-and-back-stack.jd @@ -440,13 +440,13 @@ android.app.Activity#startActivity startActivity()} 的意圖中包含旗標,

            在兩種情況下會用到親和性:

              -
            • 當啟動 Activity 的意圖包含 +
            • 當啟動 Activity 的意圖包含 {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} 旗標。

              根據預設,新的 Activity 會啟動至 Activity (名為 {@link android.app.Activity#startActivity startActivity()}) 的工作中。 系統會將它推入至與呼叫端相同的返回堆疊。 -不過,如果傳送至 +不過,如果傳送至 {@link android.app.Activity#startActivity startActivity()} 的意圖包含 {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} 旗標,則系統會找尋不同的工作來放置新的 Activity。 這通常是新工作。 @@ -455,7 +455,7 @@ android.app.Activity#startActivity startActivity()} 的意圖中包含旗標,

              如果此旗標導致 Activity 開始新的工作,而使用者按 [首頁] 按鈕離開它,必須要有方法可以讓使用者回來瀏覽這個工作。 -有些實體 (例如,通知管理員) 總是從外部工作開始 Activity,從來不使用自己的工作,因此他們都會將 {@code FLAG_ACTIVITY_NEW_TASK} 放入傳送到 +有些實體 (例如,通知管理員) 總是從外部工作開始 Activity,從來不使用自己的工作,因此他們都會將 {@code FLAG_ACTIVITY_NEW_TASK} 放入傳送到 {@link android.app.Activity#startActivity startActivity()} 的意圖。 如果您的 Activity 可以由外部實體呼叫且可能使用此旗標,記得要提供使用者獨立的方法回到啟動的工作,例如,透過啟動組件圖示 (工作的根 Activity 有一個 {@link android.content.Intent#CATEGORY_LAUNCHER} 意圖篩選器;請參閱下方的開始工作)。 @@ -505,7 +505,7 @@ href="{@docRoot}guide/topics/manifest/activity-element.html#always">alwaysRetain href="{@docRoot}guide/topics/manifest/activity-element.html#clear">clearTaskOnLaunch

              如果這項屬性在工作的根 Activity 中設為 {@code "true"},則剛描述的預設行為不會發生。 即使過了很長的一段時間,工作仍然會在堆疊保留所有的 Activity。 -換句話說,它與 +換句話說,它與 {@code alwaysRetainTaskState} 相反。即便使用者只離開工作一小段時間,使用者還是會回到工作的起始狀態。
              @@ -526,8 +526,8 @@ href="{@docRoot}guide/topics/manifest/activity-element.html#finish">finishOnTask

              開始工作

              -

              您可以給予 Activity 一個意圖篩選器,將 -{@code "android.intent.action.MAIN"} 設定為指定的動作, +

              您可以給予 Activity 一個意圖篩選器,將 +{@code "android.intent.action.MAIN"} 設定為指定的動作, {@code "android.intent.category.LAUNCHER"} 設定為指定的類別,以便將該 Activity 設定為工作的進入點。 例如:

              @@ -547,7 +547,7 @@ href="{@docRoot}guide/topics/manifest/activity-element.html#finish">finishOnTask

              第二項功能很重要:使用者必須能夠在離開工作後,使用此 Activity 啟動組件回到此工作。 -由於這個原因,兩個將 Activity 標示為一律啟動工作的啟動模式 {@code "singleTask"} 和 +由於這個原因,兩個將 Activity 標示為一律啟動工作的啟動模式 {@code "singleTask"} 和 {@code "singleInstance"},應只能在 Activity 有 {@link android.content.Intent#ACTION_MAIN} 和 {@link android.content.Intent#CATEGORY_LAUNCHER} 篩選器時才能使用。 diff --git a/docs/html-intl/intl/zh-tw/guide/topics/manifest/manifest-intro.jd b/docs/html-intl/intl/zh-tw/guide/topics/manifest/manifest-intro.jd index 5e42e37d91fc5..77a2b80d49f43 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/manifest/manifest-intro.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/manifest/manifest-intro.jd @@ -33,15 +33,15 @@ page.title=應用程式宣示說明

            • 描述應用程式的元件 — 組成應用程式的 Activity、服務、廣播接收器和內容供應程式。 -為實作每個元件的類別命名以及發佈類別的功能 (例如,類別可處理的 {@link android.content.Intent +為實作每個元件的類別命名以及發佈類別的功能 (例如,類別可處理的 {@link android.content.Intent Intent} 訊息)。 這些宣告可讓 Android 系統瞭解元件為何以及可在哪些情況下啟動。
            • -
            • 決定代管應用程式元件的程序。
            • +
            • 決定代管應用程式元件的程序。
            • 宣告應用程式必須擁有哪些權限,才能存取 API 受保護的部分以及與其他應用程式互動。 -
            • +
            • 宣示說明亦可宣告其他項目必須擁有哪些權限,才能與應用程式的元件互動。
            • @@ -66,7 +66,7 @@ Intent} 訊息)。 如要查看任一元素的詳細資訊,只要按一下圖表中的元素名稱、圖表後方按字母順序列出的元素清單,或在他處提及的任何元素名稱。 - +

              @@ -128,7 +128,7 @@ Intent} 訊息)。
               

              下方按字母順序列出可出現在宣示說明檔案中的所有元素。 只有這些才是符合資格的元素,您無法新增自己的元素或屬性。 - +

              @@ -158,7 +158,7 @@ Intent} 訊息)。

              - +

              檔案轉換

              @@ -185,7 +185,7 @@ Intent} 訊息)。

              系統通常不會將位於相同層級的元素排序。例如, <activity>、 -<provider> 和 +<provider><service> 元素能以任何順序排列組合。 ( <activity-alias> 元素是這項規則的例外狀況: @@ -218,7 +218,7 @@ Intent} 訊息)。 - +

              如果您一如往常定義元件類別 ({@link android.app.Activity}、{@link android.app.Service}、 @@ -244,7 +244,7 @@ Intent} 訊息)。 package 屬性指定)。 -下列的指派結果會和上述相同: +下列的指派結果會和上述相同:

              <manifest package="com.example.project" . . . >
              @@ -375,7 +375,7 @@ Android 會找出適當的元件來回應意圖、視需要啟動元件的新執
               <intent-filter> 元素預設值。
               
               
              -如果 
              +如果
               <application> 元素設有一個標籤,但 Activity 與其意圖篩選器並未設定該標籤,系統會將應用程式標籤視為 Activity 和意圖篩選器的標籤。
               
               
              @@ -399,7 +399,7 @@ Android 會找出適當的元件來回應意圖、視需要啟動元件的新執
               

              單一 權限 是指一項限制,可限制某部分程式碼或裝置上資料的存取權。 系統會強制實施這項限制,以保護會遭到誤用而扭曲或損害使用者體驗的重要資料與程式碼。 - +

              @@ -427,12 +427,12 @@ Android 會找出適當的元件來回應意圖、視需要啟動元件的新執 如果授予權限,該應用程式就能夠使用受保護的功能。 如果不授予權限,存取相關功能的嘗試就會失敗,但使用者不會收到任何通知。 - +

              應用程式也能利用權限來保護自己的元件 (Activity、服務、廣播接收器和內容供應程式)。 -它能使用 Android 定義的任何權限 (列於 +它能使用 Android 定義的任何權限 (列於 {@link android.Manifest.permission android.Manifest.permission}) 或其他應用程式宣告的任何權限。 此外,應用程式也能自行定義權限。新的權限是以 @@ -458,13 +458,13 @@ Android 會找出適當的元件來回應意圖、視需要啟動元件的新執

              請注意,在本範例中,不只以 -<permission> 元素宣告 {@code DEBIT_ACCT} 權限,還使用 +<permission> 元素宣告 {@code DEBIT_ACCT} 權限,還使用 <uses-permission> 元素來要求使用此權限。 即使保護是由應用程式本身強制施行,還是必須要求使用該權限,應用程式的其他元件才能啟動受保護的 Activity。 - +

              @@ -474,7 +474,7 @@ Android 會找出適當的元件來回應意圖、視需要啟動元件的新執 不過,還是必須利用 -<uses-permission> 來要求使用。 +<uses-permission> 來要求使用。

              diff --git a/docs/html-intl/intl/zh-tw/guide/topics/providers/calendar-provider.jd b/docs/html-intl/intl/zh-tw/guide/topics/providers/calendar-provider.jd index 42434e4b30e8a..682e82de80711 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/providers/calendar-provider.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/providers/calendar-provider.jd @@ -42,7 +42,7 @@ page.title=日曆供應程式

            • 使用意圖檢視日曆資料
          - +
        12. 同步配接器
        13. @@ -86,7 +86,7 @@ page.title=日曆供應程式

          -

          每個內容供應程式都會公開一個公用 URI (包裝為 +

          每個內容供應程式都會公開一個公用 URI (包裝為 {@link android.net.Uri} 物件),可唯一識別其資料集。 控制多個資料集 (多個表格) 的內容供應程式會為每個資料集公開個別的 URI。 供應程式所有 URI 的開頭字串為「content://」。 @@ -113,14 +113,14 @@ page.title=日曆供應程式

          {@link android.provider.CalendarContract.Calendars}

          此表格內含日曆特定的資訊。 此表格中的每一列包含單一日曆的詳細資訊,例如名稱、色彩、同步資訊等等。
          {@link android.provider.CalendarContract.Events}此表格內含活動特定的資訊。 此表格中的每一列包含單一活動的資訊 — 例如,活動標題、位置、開始時間、結束時間等等。 @@ -132,7 +132,7 @@ page.title=日曆供應程式
          {@link android.provider.CalendarContract.Instances}此表格內含活動每次發生的開始和結束時間。 此表格的每一列代表單一活動發生。 單次活動執行個體和活動的對應為 1:1。 @@ -141,7 +141,7 @@ page.title=日曆供應程式
          {@link android.provider.CalendarContract.Attendees}此表格內含活動參與者 (邀請對象) 的資訊。 每一列代表一個活動的單一邀請對象。 其中會指出邀請對象類型,以及邀請對象是否出席該活動的回應。 @@ -149,17 +149,17 @@ page.title=日曆供應程式
          {@link android.provider.CalendarContract.Reminders}此表格內含警示/通知資訊。 每一列代表一個活動的單一警示。一個活動可以設定多個提醒。 -每個活動的最大數量提醒指定於 +每個活動的最大數量提醒指定於 {@link android.provider.CalendarContract.CalendarColumns#MAX_REMINDERS},此項是由擁有指定日曆的同步配接器所設定。 提醒是以分鐘數指定活動發生前的時間,而且有一個方法用於決定通知使用者的方式。

          「日曆供應程式」API 的設計具備彈性且功能強大。提供良好的使用者體驗,以及保護日曆及其資料的完整性,兩者一樣重要。 @@ -178,7 +178,7 @@ page.title=日曆供應程式

        14. 同步配接器。同步配接器會將使用者裝置的日曆資料與另一台伺服器或資料來源進行同步。 -在 +在 {@link android.provider.CalendarContract.Calendars} 和 {@link android.provider.CalendarContract.Events} 表格中,會保留某些欄讓同步配接器使用。供應程式和應用程式不應加以修改。 @@ -229,7 +229,7 @@ android.Manifest.permission#READ_CALENDAR} 權限。宣示說明檔案必須包 {@link android.provider.CalendarContract.Calendars#VISIBLE} - + 指出是否選擇要顯示日曆的布林值。值 0 表示與此日曆關聯的活動不應顯示。 值 1 表示與此日曆關聯的活動應顯示。 @@ -240,7 +240,7 @@ android.provider.CalendarContract.Instances} 表格中列的產生。 {@link android.provider.CalendarContract.CalendarColumns#SYNC_EVENTS} - + 指出日曆是否應同步,並且讓日曆的活動儲存在裝置上的布林值。 值 0 表示不同步此日曆,並且不要在裝置上儲存其活動。 值 1 表示同步此日曆的活動,並且在裝置上儲存其活動。 @@ -268,18 +268,18 @@ public static final String[] EVENT_PROJECTION = new String[] { Calendars.CALENDAR_DISPLAY_NAME, // 2 Calendars.OWNER_ACCOUNT // 3 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1; private static final int PROJECTION_DISPLAY_NAME_INDEX = 2; private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3; - + +

          在範例的下一個部分,您將建構查詢。選項會指定查詢的條件。 @@ -308,49 +308,49 @@ android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL} 帳戶不會進行同步

          // Run query
           Cursor cur = null;
           ContentResolver cr = getContentResolver();
          -Uri uri = Calendars.CONTENT_URI;   
          -String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" 
          +Uri uri = Calendars.CONTENT_URI;
          +String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND ("
                                   + Calendars.ACCOUNT_TYPE + " = ?) AND ("
                                   + Calendars.OWNER_ACCOUNT + " = ?))";
           String[] selectionArgs = new String[] {"sampleuser@gmail.com", "com.google",
          -        "sampleuser@gmail.com"}; 
          -// Submit the query and get a Cursor object back. 
          +        "sampleuser@gmail.com"};
          +// Submit the query and get a Cursor object back.
           cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);

          下一節會使用游標逐步檢視結果集。它會使用範例一開始設定好的常數,傳回每個欄位的值。

          - +
          // Use the cursor to step through the returned records
           while (cur.moveToNext()) {
               long calID = 0;
               String displayName = null;
               String accountName = null;
               String ownerName = null;
          -      
          +
               // Get the field values
               calID = cur.getLong(PROJECTION_ID_INDEX);
               displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
               accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
               ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
          -              
          +
               // Do something with the values...
           
              ...
           }
           
          - +

          修改日曆

          如要執行日曆的更新,您可以提供日曆的 {@link -android.provider.BaseColumns#_ID},可以是 URI 的附加 ID +android.provider.BaseColumns#_ID},可以是 URI 的附加 ID ({@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) 或以第一個選擇項目方式提供。 -選項的開頭應該是 "_id=?",而且第一個 +選項的開頭應該是 "_id=?",而且第一個 selectionArg 應該是日曆的 {@link android.provider.BaseColumns#_ID}。 -您也可以透過將 ID 編碼在 URI 中,以執行更新。此範例會使用 +您也可以透過將 ID 編碼在 URI 中,以執行更新。此範例會使用 ({@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) 方式變更日曆的顯示名稱: @@ -434,7 +434,7 @@ android.provider.CalendarContract.Events} 參照。

          {@link android.provider.CalendarContract.EventsColumns#DURATION} - + 活動的持續期間,以 RFC5545 格式表示。例如,值 "PT1H" 表示活動持續一小時,而值 "P2W" 指出持續 2 週。 @@ -444,24 +444,24 @@ android.provider.CalendarContract.Events} 參照。

          {@link android.provider.CalendarContract.EventsColumns#ALL_DAY} - + 值 1 表示此活動需要整天,如同當地時區所定義。 值 0 表示定期活動,會在一天中的任何時間開始和結束。 - + - - + + {@link android.provider.CalendarContract.EventsColumns#RRULE} - + 活動的週期規則。例如,"FREQ=WEEKLY;COUNT=10;WKST=SU"。 您可以在這裡查看更多範例。 - + - + {@link android.provider.CalendarContract.EventsColumns#RDATE} 活動重複發生的日期。您通常會將 {@link android.provider.CalendarContract.EventsColumns#RDATE} 和 {@link android.provider.CalendarContract.EventsColumns#RRULE} 一起使用,以定義週期性活動的彙總集合。 @@ -470,13 +470,13 @@ android.provider.CalendarContract.Events} 參照。

          如需更多討論,請參閱 RFC5545 規格。 - + {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY} - + 活動要視為忙碌或有空 (可以安排其他活動) 的時間。 - + {@link android.provider.CalendarContract.EventsColumns#GUESTS_CAN_MODIFY} @@ -494,7 +494,7 @@ android.provider.CalendarContract.Events} 參照。

          新增活動

          -

          您的應用程式插入新活動時,我們建議您使用 +

          您的應用程式插入新活動時,我們建議您使用 {@link android.content.Intent#ACTION_INSERT INSERT} 意圖 (如同使用意圖插入活動所述)。不過,如果需要,您也可以直接插入活動。 本節將描述如何執行此動作。

          @@ -514,11 +514,11 @@ java.util.TimeZone#getAvailableIDs()}。 android.content.Intent#ACTION_INSERT INSERT} 意圖 (如同使用意圖插入活動 — 所描述的案例) 插入活動,則不適用此規則,將會提供預設時區。
        15. - +
        16. 對於非週期性活動,您必須包括 {@link android.provider.CalendarContract.EventsColumns#DTEND}。
        17. - - + +
        18. 對於週期性活動,您必須包括 {@link android.provider.CalendarContract.EventsColumns#DURATION},以及 {@link android.provider.CalendarContract.EventsColumns#RRULE} 或 {@link @@ -528,7 +528,7 @@ android.provider.CalendarContract.EventsColumns#RRULE} 搭配 {@link android.pro
        19. - +

      以下是插入活動的範例。為了簡化,會在 UI 執行緒中執行此示範。 @@ -539,8 +539,8 @@ android.provider.CalendarContract.EventsColumns#RRULE} 搭配 {@link android.pro

       long calID = 3;
      -long startMillis = 0; 
      -long endMillis = 0;     
      +long startMillis = 0;
      +long endMillis = 0;
       Calendar beginTime = Calendar.getInstance();
       beginTime.set(2012, 9, 14, 7, 30);
       startMillis = beginTime.getTimeInMillis();
      @@ -561,7 +561,7 @@ Uri uri = cr.insert(Events.CONTENT_URI, values);
       
       // get the event ID that is the last element in the Uri
       long eventID = Long.parseLong(uri.getLastPathSegment());
      -// 
      +//
       // ... do something with event ID
       //
       //
      @@ -581,11 +581,11 @@ long eventID = Long.parseLong(uri.getLastPathSegment()); android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) 或以第一個選擇項目方式提供。 -選項的開頭應該是 "_id=?",而且第一個 +選項的開頭應該是 "_id=?",而且第一個 selectionArg 應該是活動的 _ID。 您也可以使用不含 ID 的選項進行更新。以下是更新活動的範例。 -它使用 +它使用 {@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()} 方式變更活動的標題:

      @@ -598,7 +598,7 @@ ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); Uri updateUri = null; // The new title for the event -values.put(Events.TITLE, "Kickboxing"); +values.put(Events.TITLE, "Kickboxing"); updateUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID); int rows = getContentResolver().update(updateUri, values, null, null); Log.i(DEBUG_TAG, "Rows updated: " + rows); @@ -625,19 +625,19 @@ ContentValues values = new ContentValues(); Uri deleteUri = null; deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID); int rows = getContentResolver().delete(deleteUri, null, null); -Log.i(DEBUG_TAG, "Rows deleted: " + rows); +Log.i(DEBUG_TAG, "Rows deleted: " + rows);

      參與者表格

      {@link android.provider.CalendarContract.Attendees} 表格的每一列都代表活動的單一參與者或邀請對象。 -呼叫 +呼叫 {@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} 會傳回指定 {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} 活動的參與者清單。 此 {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} 必須符合特定活動的 {@link android.provider.BaseColumns#_ID}。 -

      +

      下表列出可寫入的欄位。 插入新的參與者時,您必須包括 ATTENDEE_NAME 以外的所有項目。 @@ -718,8 +718,8 @@ Uri uri = cr.insert(Attendees.CONTENT_URI, values);

      提醒表格

      {@link android.provider.CalendarContract.Reminders} 表格的每一列都代表活動的單一提醒。 -呼叫 -{@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} 會傳回指定 +呼叫 +{@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} 會傳回指定 {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} 活動的提醒清單。

      @@ -727,7 +727,7 @@ Uri uri = cr.insert(Attendees.CONTENT_URI, values);

      下表列出提醒可寫入的欄位。插入新的提醒時,必須包括所有項目。 請注意,同步配接器會在 {@link android.provider.CalendarContract.Calendars} 表格中指出同步配接器支援的提醒類型。 -如需詳細資料,請參閱 +如需詳細資料,請參閱 {@link android.provider.CalendarContract.CalendarColumns#ALLOWED_REMINDERS}。

      @@ -779,8 +779,8 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values); 執行個體表格無法寫入,僅供查詢活動的發生。

      -

      下表列出您可以針對執行個體查詢的欄位。請注意,時區是由 -{@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} 和 +

      下表列出您可以針對執行個體查詢的欄位。請注意,時區是由 +{@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} 和 {@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_INSTANCES} 所定義。

      @@ -801,18 +801,18 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values); {@link android.provider.CalendarContract.Instances#END_DAY} - + 執行個體的凱撒曆結束日,與「日曆」的時區相關。 - - + + {@link android.provider.CalendarContract.Instances#END_MINUTE} - + 執行個體的結束分鐘,從「日曆」時區的午夜開始計算。 - + {@link android.provider.CalendarContract.Instances#EVENT_ID} @@ -820,16 +820,16 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values); {@link android.provider.CalendarContract.Instances#START_DAY} - 執行個體的凱撒曆開始日,與「日曆」的時區相關。 + 執行個體的凱撒曆開始日,與「日曆」的時區相關。 {@link android.provider.CalendarContract.Instances#START_MINUTE} - + 執行個體的開始分鐘,從午夜開始計算,與「日曆」的時區相關。 - + - + @@ -853,7 +853,7 @@ public static final String[] INSTANCE_PROJECTION = new String[] { Instances.BEGIN, // 1 Instances.TITLE // 2 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_BEGIN_INDEX = 1; @@ -868,7 +868,7 @@ long startMillis = beginTime.getTimeInMillis(); Calendar endTime = Calendar.getInstance(); endTime.set(2011, 10, 24, 8, 0); long endMillis = endTime.getTimeInMillis(); - + Cursor cur = null; ContentResolver cr = getContentResolver(); @@ -883,28 +883,28 @@ ContentUris.appendId(builder, startMillis); ContentUris.appendId(builder, endMillis); // Submit the query -cur = cr.query(builder.build(), - INSTANCE_PROJECTION, - selection, - selectionArgs, +cur = cr.query(builder.build(), + INSTANCE_PROJECTION, + selection, + selectionArgs, null); - + while (cur.moveToNext()) { String title = null; long eventID = 0; - long beginVal = 0; - + long beginVal = 0; + // Get the field values eventID = cur.getLong(PROJECTION_ID_INDEX); beginVal = cur.getLong(PROJECTION_BEGIN_INDEX); title = cur.getString(PROJECTION_TITLE_INDEX); - - // Do something with the values. - Log.i(DEBUG_TAG, "Event: " + title); + + // Do something with the values. + Log.i(DEBUG_TAG, "Event: " + title); Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(beginVal); + calendar.setTimeInMillis(beginVal); DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); - Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); + Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); } } @@ -922,9 +922,9 @@ while (cur.moveToNext()) {
      {@link android.content.Intent#ACTION_VIEW VIEW}

      content://com.android.calendar/time/<ms_since_epoch>

      - 您也可以使用 + 您也可以使用 {@link android.provider.CalendarContract#CONTENT_URI CalendarContract.CONTENT_URI} 參照 URI。如需使用此意圖的範例,請參閱使用意圖檢視日曆資料。 - + 開啟日曆到 <ms_since_epoch> 指定的時間。 @@ -935,11 +935,11 @@ while (cur.moveToNext()) {

      content://com.android.calendar/events/<event_id>

      - - 您也可以使用 + + 您也可以使用 {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} 參照 URI。如需使用此意圖的範例,請參閱使用意圖檢視日曆資料。 - + 檢視 <event_id> 指定的活動。 @@ -952,12 +952,12 @@ while (cur.moveToNext()) { {@link android.content.Intent#ACTION_EDIT EDIT}

      content://com.android.calendar/events/<event_id>

      - - 您也可以使用 + + 您也可以使用 {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} 參照 URI。如需使用此意圖的範例,請參閱使用意圖編輯活動。 - - + + 編輯 <event_id> 指定的活動。 @@ -972,11 +972,11 @@ while (cur.moveToNext()) {
      {@link android.content.Intent#ACTION_INSERT INSERT}

      content://com.android.calendar/events

      - - 您也可以使用 + + 您也可以使用 {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} 參照 URI。如需使用此意圖的範例,請參閱使用意圖插入活動。 - + 建立活動。 @@ -996,7 +996,7 @@ while (cur.moveToNext()) { 活動的名稱。 - + {@link android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME} 活動開始時間,以紀元元年 1 月 1 日零時起算經過的毫秒數為單位。 @@ -1004,25 +1004,25 @@ CalendarContract.EXTRA_EVENT_BEGIN_TIME} {@link android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME} - + 活動結束時間,以紀元元年 1 月 1 日零時起算經過的毫秒數為單位。 {@link android.provider.CalendarContract#EXTRA_EVENT_ALL_DAY CalendarContract.EXTRA_EVENT_ALL_DAY} - - 指出活動為整天的布林值。值可以是 + + 指出活動為整天的布林值。值可以是 truefalse。 {@link android.provider.CalendarContract.EventsColumns#EVENT_LOCATION Events.EVENT_LOCATION} - + 活動的地點。 {@link android.provider.CalendarContract.EventsColumns#DESCRIPTION Events.DESCRIPTION} - + 活動描述。 @@ -1039,16 +1039,16 @@ Events.DESCRIPTION} {@link android.provider.CalendarContract.EventsColumns#ACCESS_LEVEL Events.ACCESS_LEVEL} - + 活動為私人或公開性質。 {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY Events.AVAILABILITY} - + 活動要視為忙碌或有空 (可以安排其他活動) 的時間。 - - + +

      以下各節說明如何使用這些意圖。

      @@ -1059,14 +1059,14 @@ android.Manifest.permission#WRITE_CALENDAR} 權限包括在其SampleSyncAdapter。 diff --git a/docs/html-intl/intl/zh-tw/guide/topics/providers/contacts-provider.jd b/docs/html-intl/intl/zh-tw/guide/topics/providers/contacts-provider.jd index b5f888012eed2..2bcc3e62b3d33 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/providers/contacts-provider.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/providers/contacts-provider.jd @@ -614,7 +614,7 @@ Email.CONTENT_ITEM_TYPE} (內含使用者名稱,而不是電子郵件地址)

      如要擷取內含使用者的設定檔的聯絡人列,請呼叫 {@link android.content.ContentResolver#query(Uri,String[], String, String[], String) ContentResolver.query()}。 -將內容 URI 設為 +將內容 URI 設為 {@link android.provider.ContactsContract.Profile#CONTENT_URI},並且不要提供任何選取條件。 您也可以使用此內容 URI 做為擷取原始聯絡人或設定檔資料的基礎 URI。 例如,以下程式碼片段會擷取設定檔資料: @@ -932,7 +932,7 @@ public Loader<Cursor> onCreateLoader(int id, Bundle args) { 您應該儘可能透過建立 {@link android.content.ContentProviderOperation} 物件的{@link java.util.ArrayList},然後呼叫 {@link android.content.ContentResolver#applyBatch(String, ArrayList) applyBatch()},以「批次模式」在聯絡人供應程式中進行資料的插入、更新以及刪除。 -因為聯絡人供應程式會在單一交易中執行 +因為聯絡人供應程式會在單一交易中執行 {@link android.content.ContentResolver#applyBatch(String, ArrayList) applyBatch()} 的所有操作,所以您所做的修改不會讓聯絡人存放庫處於不一致的狀態。 @@ -1004,7 +1004,7 @@ public Loader<Cursor> onCreateLoader(int id, Bundle args) { previousResult

      - + {@link android.content.ContentResolver#applyBatch(String, ArrayList) applyBatch()} 中的 {@link android.content.ContentProviderResult} 物件以 0 開始的陣列索引值。套用批次操作時,每次操作結果都會儲存在結果的中繼陣列。 @@ -1758,7 +1758,7 @@ onPerformSync()} 方法完成。
      {@link android.accounts.AccountManager} 會啟動此服以開始驗證程序。 服務的 {@link android.app.Service#onCreate()} 方法會具現化為驗證器物件。 -系統需驗證應用程式同步配接器的使用者帳戶時,會呼叫服務的 +系統需驗證應用程式同步配接器的使用者帳戶時,會呼叫服務的 {@link android.app.Service#onBind(Intent) onBind()} 方法以取得驗證器的 {@link android.os.IBinder}。 這樣可以讓系統以跨處理程序的方式呼叫驗證器的方法。 @@ -2115,7 +2115,7 @@ openAssetFileDescriptor()} 可取得相片檔案的控制代碼。
    activityclass 值是 Activity 的完整類別名稱,以此 Activity 接收意圖。 invite_action_label 值是顯示在裝置聯絡人應用程式內 [新增連線] 選單中的文字字串。 - + diff --git a/docs/html-intl/intl/zh-tw/guide/topics/providers/content-provider-basics.jd b/docs/html-intl/intl/zh-tw/guide/topics/providers/content-provider-basics.jd index 78314784ba9e1..a00caed1f4350 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/providers/content-provider-basics.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/providers/content-provider-basics.jd @@ -237,7 +237,7 @@ page.title=內容供應程式基本概念 {@link android.content.ContentResolver#query query()} 方法會呼叫使用者字典供應程式所定義的 {@link android.content.ContentProvider#query ContentProvider.query()} 方法。 -以下是 +以下是 {@link android.content.ContentResolver#query ContentResolver.query()} 呼叫的程式碼:

    @@ -250,7 +250,7 @@ mCursor = getContentResolver().query(
         mSortOrder);                        // The sort order for the returned rows
     

    - 表 2 列出 + 表 2 列出 {@link android.content.ContentResolver#query query(Uri,projection,selection,selectionArgs,sortOrder)} 的引數及相對應的 SQL SELECT 陳述式:

    @@ -284,7 +284,7 @@ query(Uri,projection,selection,selectionArgs,sortOrder)} 的引數及相對應 selectionArgs - (沒有任何相對應的關鍵字/參數。選取引數會取代選取子句中的 + (沒有任何相對應的關鍵字/參數。選取引數會取代選取子句中的 ? 預留位置。) @@ -581,7 +581,7 @@ selectionArgs[0] = mUserInput;

    - 如果沒有任何資料欄符合選取條件,則供應程式會傳回 {@link android.database.Cursor#getCount Cursor.getCount()} 為 0 的 + 如果沒有任何資料欄符合選取條件,則供應程式會傳回 {@link android.database.Cursor#getCount Cursor.getCount()} 為 0 的 {@link android.database.Cursor} 物件 (即沒有任何內容的游標)。

    @@ -595,7 +595,7 @@ selectionArgs[0] = mUserInput;

    - 以下程式碼片段是上一個程式碼片段的延伸。它會建立內含查詢所擷取 {@link android.database.Cursor} 的 + 以下程式碼片段是上一個程式碼片段的延伸。它會建立內含查詢所擷取 {@link android.database.Cursor} 的 {@link android.widget.SimpleCursorAdapter} 物件,並將該物件設定為 {@link android.widget.ListView} 的配接器: @@ -674,7 +674,7 @@ if (mCursor != null) {

    {@link android.database.Cursor} 實作方法包含數個用於從物件擷取不同資料類型的「get」方法。 例如,上方程式碼片段使用了 {@link android.database.Cursor#getString getString()}。 -此外,這種實作方法還包括 +此外,這種實作方法還包括 {@link android.database.Cursor#getType getType()} 方法,可傳回指定資料欄資料類型的值。

    @@ -709,7 +709,7 @@ if (mCursor != null) {

    - 以下的 + 以下的 <uses-permission> 元素會要求使用者字典供應程式的讀取存取權:

    @@ -733,7 +733,7 @@ if (mCursor != null) {

    插入資料

    - 如要在供應程式中插入資料,請呼叫 + 如要在供應程式中插入資料,請呼叫 {@link android.content.ContentResolver#insert ContentResolver.insert()} 方法。 這個方法會在供應程式中插入新的資料列,並傳回該列的內容 URI。 以下程式碼片段示範如何在使用者字典供應程式中插入新的字詞: @@ -785,14 +785,14 @@ content://user_dictionary/words/<id_value>

    - 如要從傳回的 {@link android.net.Uri} 取得 _ID 的值,請呼叫 + 如要從傳回的 {@link android.net.Uri} 取得 _ID 的值,請呼叫 {@link android.content.ContentUris#parseId ContentUris.parseId()}。

    更新資料

    如要更新資料列,請使用內含經過更新的值 (與您在插入資料時所使用的值相同) 以及選取條件 (與您在建立查詢時所使用的選取條件相同) 的 {@link android.content.ContentValues} 物件。 - 您所使用的用戶端方法為 + 您所使用的用戶端方法為 {@link android.content.ContentResolver#update ContentResolver.update()}。您只需針對要更新的資料欄,將相關值加到 {@link android.content.ContentValues} 物件即可。 如果您想清除資料欄的內容,請將值設定為 null。 @@ -901,7 +901,7 @@ Cursor.getType()} 來確認可用的資料類型。 例如,聯絡人供應程式中的 {@link android.provider.ContactsContract.Data} 表格會使用 MIME 類型為每個資料列中儲存的聯絡人資料加上標籤。 -如要取得與內容 URI 相對應的 MIME 類型,請呼叫 +如要取得與內容 URI 相對應的 MIME 類型,請呼叫 {@link android.content.ContentResolver#getType ContentResolver.getType()}。

    @@ -1009,13 +1009,13 @@ ContentResolver.applyBatch()},則系統會傳回一系列結果。

    - 供應程式會使用 + 供應程式會使用 <provider> - 元素的 + 元素的 android:grantUriPermission - 屬性以及 + 屬性以及 <provider> - 元素的 + 元素的 <grant-uri-permission> 子元素在本身的宣示說明中為內容 URI 定義 URI 權限。如要進一步瞭解 URI 權限的運作機制,請參閱安全性和權限指南的「URI 權限」。 @@ -1032,8 +1032,8 @@ ContentResolver.applyBatch()},則系統會傳回一系列結果。

    1. 您的應用程式使用 {@link android.app.Activity#startActivityForResult -startActivityForResult()} 方法,傳送了內含 -{@link android.content.Intent#ACTION_PICK} 動作的意圖以及「聯絡人」MIME 類型 +startActivityForResult()} 方法,傳送了內含 +{@link android.content.Intent#ACTION_PICK} 動作的意圖以及「聯絡人」MIME 類型 {@link android.provider.ContactsContract.RawContacts#CONTENT_ITEM_TYPE}。
    2. @@ -1043,9 +1043,9 @@ startActivityForResult()} 方法,傳送了內含
    3. 在選取 Activity 中,使用者選取了要更新的聯絡人。 -一旦使用者進行這項動作,選取 Activity 便會呼叫 +一旦使用者進行這項動作,選取 Activity 便會呼叫 {@link android.app.Activity#setResult setResult(resultcode, intent)} 來設定要傳回您應用程式的意圖。 -該意圖包含使用者所選聯絡人的內容 URI,以及「額外」的旗標 +該意圖包含使用者所選聯絡人的內容 URI,以及「額外」的旗標 {@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION}。 這些旗標可將 URI 權限授予您的應用程式,以便其讀取內容 URI 指向的聯絡人資料。選取 Activity 隨後會呼叫 {@link android.app.Activity#finish()} 來傳回您應用程式的控制權。 @@ -1053,7 +1053,7 @@ startActivityForResult()} 方法,傳送了內含
    4. - 您的 Activity 返回前景,而系統呼叫您 Activity 的 + 您的 Activity 返回前景,而系統呼叫您 Activity 的 {@link android.app.Activity#onActivityResult onActivityResult()} 方法。 這個方法可接收聯絡人應用程式中的選取 Activity 所建立的結果意圖。 @@ -1071,7 +1071,7 @@ startActivityForResult()} 方法,傳送了內含

      - 例如,日曆應用程式接受可讓您啟用應用程式插入 UI 的 + 例如,日曆應用程式接受可讓您啟用應用程式插入 UI 的 {@link android.content.Intent#ACTION_INSERT} 意圖。您可以在該意圖中傳入「額外」的資料,供應用程式用於預先填入使用者介面。由於週期性活動的語法較為複雜,因此建議您利用 {@link android.content.Intent#ACTION_INSERT} 啟用日曆應用程式,然後讓使用者透過該應用程式將活動插入日曆供應程式。 @@ -1089,7 +1089,7 @@ Android 平台內建的大多數供應程式都可在 {@link android.provider}

      例如,使用者字典供應程式有一個內含內容 URI 和欄名稱常數的 {@link android.provider.UserDictionary} 合約類別。 -「字詞」表格的內容 URI 是在 +「字詞」表格的內容 URI 是在 {@link android.provider.UserDictionary.Words#CONTENT_URI UserDictionary.Words.CONTENT_URI} 常數中定義。 此外,{@link android.provider.UserDictionary.Words} 類別也包含欄名稱常數,可用於本指南中的程式碼片段範例。 @@ -1106,7 +1106,7 @@ String[] mProjection =

      聯絡人供應程式的另一個合約類別為 {@link android.provider.ContactsContract}。 - 此類別的參考文件附有程式碼片段範例。其中一個 + 此類別的參考文件附有程式碼片段範例。其中一個 {@link android.provider.ContactsContract.Intents.Insert} 子類別為內含意圖常數和意圖資料的合約類別。

      diff --git a/docs/html-intl/intl/zh-tw/guide/topics/providers/content-provider-creating.jd b/docs/html-intl/intl/zh-tw/guide/topics/providers/content-provider-creating.jd index 3d46ee4b4c809..9f1ca3176af16 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/providers/content-provider-creating.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/providers/content-provider-creating.jd @@ -239,7 +239,7 @@ page.title=建立內容供應程式 表格資料一律需包含「主索引鍵」欄,方便供應程式保存每個資料列的數值。 您可以使用這些值將資料列連結至其他表格中的相關資料列 (也就是將這些值當作「外部索引鍵」使用)。 事實上,您也可以使用此資料欄的任何名稱進行連結,但使用 {@link android.provider.BaseColumns#_ID BaseColumns._ID} 是最佳做法,這是因為將供應程式的查詢結果連結至 -{@link android.widget.ListView} 時需要將某個擷取出的資料列命名為 +{@link android.widget.ListView} 時需要將某個擷取出的資料列命名為 _ID。 @@ -288,14 +288,14 @@ MIME 類型欄中的值會決定 BLOB 欄的資料定義, 此外,也請針對 Android 套件名稱採取此建議做法;您可以將供應程式授權定義為內含供應程式的套件名稱的副檔名。 例如,假設您 Android 套件的名稱為 - com.example.<appname>,則請將供應程式的授權定義為 + com.example.<appname>,則請將供應程式的授權定義為 com.example.<appname>.provider

      設計路徑結構

      開發人員通常只要附加指向個別表格的路徑,即可從授權建立內容 URI。 -例如,假設您有「table1」和「table2」這兩個表格,則您可以結合上述範例中的授權來產生內容 URI -com.example.<appname>.provider/table1 和 +例如,假設您有「table1」和「table2」這兩個表格,則您可以結合上述範例中的授權來產生內容 URI +com.example.<appname>.provider/table1com.example.<appname>.provider/table2。 路徑並不侷限於單一區隔,而您也不必為每個路徑層級產生表格。 @@ -350,11 +350,11 @@ MIME 類型欄中的值會決定 BLOB 欄的資料定義, content://com.example.app.provider/table1:名稱為 table1 的表格。

    5. - content://com.example.app.provider/table2/dataset1:名稱為 + content://com.example.app.provider/table2/dataset1:名稱為 dataset1 的表格。
    6. - content://com.example.app.provider/table2/dataset2:名稱為 + content://com.example.app.provider/table2/dataset2:名稱為 dataset2 的表格。
    7. @@ -380,7 +380,7 @@ MIME 類型欄中的值會決定 BLOB 欄的資料定義, content://com.example.app.provider/table2/*
      - 與 dataset1dataset2 表格的內容 URI 相符,但與 table1 或 + 與 dataset1dataset2 表格的內容 URI 相符,但與 table1table3 的內容 URI 不符。
      @@ -393,8 +393,8 @@ MIME 類型欄中的值會決定 BLOB 欄的資料定義,

      以下程式碼片段說明各種方法在 {@link android.content.UriMatcher} 中的運作方式。 - 這個程式碼會以不同方式處理整個表格的 URI 以及單一資料列的 URI;針對表格使用內容 URI 模式 -content://<authority>/<path>,針對單一資料列則使用 + 這個程式碼會以不同方式處理整個表格的 URI 以及單一資料列的 URI;針對表格使用內容 URI 模式 +content://<authority>/<path>,針對單一資料列則使用 content://<authority>/<path>/<id>

      @@ -469,8 +469,8 @@ public class ExampleProvider extends ContentProvider {

      另一個 {@link android.content.ContentUris} 類別可提供使用內容 URI 的 id 部分的簡便方法。 -{@link android.net.Uri} 和 -{@link android.net.Uri.Builder} 類別則可提供剖析現有 +{@link android.net.Uri} 和 +{@link android.net.Uri.Builder} 類別則可提供剖析現有 {@link android.net.Uri} 物件及建置新物件的簡便方法。

      @@ -485,7 +485,7 @@ public class ExampleProvider extends ContentProvider {

      必要方法

      抽象類別 {@link android.content.ContentProvider} 會定義 6 種方法,而您必須將這些方法實作成您所擁有子類別的一部分。 -嘗試存取您內容供應程式的用戶端應用程式會呼叫以下所有方法 +嘗試存取您內容供應程式的用戶端應用程式會呼叫以下所有方法 ({@link android.content.ContentProvider#onCreate() onCreate()} 除外):

      @@ -539,7 +539,7 @@ public class ExampleProvider extends ContentProvider {

      - 請注意,上述方法採用的簽名與同名的 + 請注意,上述方法採用的簽名與同名的 {@link android.content.ContentResolver} 方法相同。

      @@ -641,7 +641,7 @@ Android 可以針對下列例外狀況執行這項動作,藉此協助解決查

      - 例如,如果您採用 SQLite 資料庫,您可以透過 + 例如,如果您採用 SQLite 資料庫,您可以透過 {@link android.content.ContentProvider#onCreate() ContentProvider.onCreate()} 建立新的 {@link android.database.sqlite.SQLiteOpenHelper} 物件,然後在初次開啟資料庫時建立 SQL 表格。 為了加快這個程序,當您初次呼叫 {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase @@ -651,10 +651,10 @@ SQLiteOpenHelper.onCreate()} 方法。

      - 以下兩個程式碼片段展示了 + 以下兩個程式碼片段展示了 {@link android.content.ContentProvider#onCreate() ContentProvider.onCreate()} 與 {@link android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase) SQLiteOpenHelper.onCreate()} 之間的互動過程。 -而第一個程式碼片段是用於實作 +而第一個程式碼片段是用於實作 {@link android.content.ContentProvider#onCreate() ContentProvider.onCreate()}:

      @@ -808,7 +808,7 @@ protected static final class MainDatabaseHelper extends SQLiteOpenHelper {
                   <name> 必須是全域唯一值,而 <type> 必須為相對應 URI 模式的專屬值。
       
       建議您使用貴公司的名稱或您應用程式的部分 Android 套件名稱做為 <name>。
      -針對 
      +針對
       <type>,則建議您使用可識別與 URI 相關的表格的字串。
       
               

      @@ -816,8 +816,8 @@ protected static final class MainDatabaseHelper extends SQLiteOpenHelper {
    8. - 例如,假設供應程式的授權為 -com.example.app.provider,而該授權可提供 + 例如,假設供應程式的授權為 +com.example.app.provider,而該授權可提供 table1 這個表格,則 table1 中多個資料列的 MIME 類型會如下所示:

      @@ -940,7 +940,7 @@ ContentProvider.getStreamTypes()} 會傳回如下所示的陣列:
       為了將權限設為僅適用於您的供應程式,請針對
        
           android:name 屬性使用 Java 式範圍。
      -例如,請將讀取權限命名為 
      +例如,請將讀取權限命名為
       com.example.app.provider.permission.READ_PROVIDER

      @@ -955,7 +955,7 @@ ContentProvider.getStreamTypes()} 會傳回如下所示的陣列:
      這項權限是由 - <provider> 元素的 + <provider> 元素的 android:permission 屬性所指定,可控制整個供應程式的讀取及寫入存取權。 @@ -967,10 +967,10 @@ ContentProvider.getStreamTypes()} 會傳回如下所示的陣列: 整個供應程式的讀取權限及寫入權限。您可以使用 <provider> 元素的 - android:readPermission 和 + android:readPermission 和 android:writePermission 屬性指定這兩項權限。 -這些權限的優先等級比 +這些權限的優先等級比 android:permission 所需的權限來得高。
      @@ -1037,9 +1037,9 @@ Context.revokeUriPermission()}。

      - 如要將臨時存取權委派給某款應用程式,您就必須在意圖中加入 -{@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} 或 -{@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} 旗標,或是同時加入以上兩者。請使用 + 如要將臨時存取權委派給某款應用程式,您就必須在意圖中加入 +{@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} 或 +{@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} 旗標,或是同時加入以上兩者。請使用 {@link android.content.Intent#setFlags(int) setFlags()} 方法設定這些旗標。

      @@ -1187,7 +1187,7 @@ Context.revokeUriPermission()}。

      意圖和資料存取權

      應用程式可透過 {@link android.content.Intent} 以間接方式存取內容供應程式。 - 利用這種存取方式的應用程式不會呼叫 {@link android.content.ContentResolver} 或 + 利用這種存取方式的應用程式不會呼叫 {@link android.content.ContentResolver} 或 {@link android.content.ContentProvider} 的任何方法,而是會傳送可啟動 Activity (此 Activity 通常屬於供應程式本身的應用程式) 的意圖。 目標 Activity 會負責擷取資料並在本身的 UI 中顯示該資料。視意圖中的動作而定,目標 Activity 也可能會提示使用者修改供應程式的資料。 diff --git a/docs/html-intl/intl/zh-tw/guide/topics/providers/document-provider.jd b/docs/html-intl/intl/zh-tw/guide/topics/providers/document-provider.jd index 1dc7c46f43873..a6af7586b8847 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/providers/document-provider.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/providers/document-provider.jd @@ -213,7 +213,7 @@ Android 4.4 儲存空間存取架構:用戶端

      -

      針對搭載 Android 4.4 以上版本的裝置,您的應用程式還可以呼叫 +

      針對搭載 Android 4.4 以上版本的裝置,您的應用程式還可以呼叫 {@link android.content.Intent#ACTION_OPEN_DOCUMENT} 意圖,以顯示系統所控管的挑選器 UI,方便使用者瀏覽其他應用程式提供的所有檔案。 透過這個單一 UI,使用者可以從任何受支援的應用程式挑選檔案。 @@ -560,7 +560,7 @@ getContentResolver().takePersistableUriPermission(uri, takeFlags);

    9. 供應程式的名稱 (也就是供應程式的類別名稱),包括套件名稱。範例:com.example.android.storageprovider.MyCloudProvider
    10. -
    11. 授權的名稱 (也就是套件的名稱;在此範例中為 +
    12. 授權的名稱 (也就是套件的名稱;在此範例中為 com.example.android.storageprovider) 以及內容供應程式的類型 (documents)。範例:{@code com.example.android.storageprovider.documents}。
    13. @@ -588,7 +588,7 @@ getContentResolver().takePersistableUriPermission(uri, takeFlags);
      <bool name="atLeastKitKat">true</bool>
      -
    14. 內含 +
    15. 內含 {@code android.content.action.DOCUMENTS_PROVIDER} 動作的意圖篩選器,讓您的供應程式能夠在系統搜尋供應程式時顯示在挑選器中。
    16. @@ -618,7 +618,7 @@ getContentResolver().takePersistableUriPermission(uri, takeFlags);

      支援搭載 Android 4.3 以下版本的裝置

      -

      只有搭載 Android 4.4 以上版本的裝置可使用 +

      只有搭載 Android 4.4 以上版本的裝置可使用 {@link android.content.Intent#ACTION_OPEN_DOCUMENT} 意圖。如果您想讓應用程式支援 {@link android.content.Intent#ACTION_GET_CONTENT} 以便與搭載 Android 4.3 以下版本的裝置相容,請針對搭載 Android 4.4 以上版本的裝置停用宣示說明中的 {@link android.content.Intent#ACTION_GET_CONTENT} 意圖篩選器。 @@ -833,7 +833,7 @@ public Cursor queryDocument(String documentId, String[] projection) throws

      實作 openDocument

      您必須實作 {@link android.provider.DocumentsProvider#openDocument -openDocument()} 來傳回代表特定檔案的 +openDocument()} 來傳回代表特定檔案的 {@link android.os.ParcelFileDescriptor}。其他應用程式可利用傳回的 {@link android.os.ParcelFileDescriptor} 傳輸資料。 使用者選取檔案而且用戶端應用程式呼叫 {@link android.content.ContentResolver#openFileDescriptor openFileDescriptor()} 要求存取該檔案後,系統就會呼叫這個方法。範例: diff --git a/docs/html-intl/intl/zh-tw/guide/topics/resources/accessing-resources.jd b/docs/html-intl/intl/zh-tw/guide/topics/resources/accessing-resources.jd index 3a5a96121d942..d1ac69cde5dbf 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/resources/accessing-resources.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/resources/accessing-resources.jd @@ -101,12 +101,12 @@ android.content.res.Resources} (以 {@link android.content.Context#getResources(

      有些裝置設定可以在執行階段期間進行變更 (例如,螢幕方向、鍵盤可用性和語言)。 -進行這類變更時,Android 會重新啟動執行中的 +進行這類變更時,Android 會重新啟動執行中的 {@link android.app.Activity} (呼叫 {@link android.app.Activity#onDestroy()},後面加上 {@link android.app.Activity#onCreate(Bundle) onCreate()})。 重新啟動行為的設計是以符合新裝置設定的替代資源自動重新載入您的應用程式,以協助您的應用程式適應新的設定。 diff --git a/docs/html-intl/intl/zh-tw/guide/topics/ui/controls.jd b/docs/html-intl/intl/zh-tw/guide/topics/ui/controls.jd index 0f27ae4e8803f..1ab66c3f12f3a 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/ui/controls.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/ui/controls.jd @@ -69,7 +69,7 @@ parent.link=index.html 圓形按鈕 功用與核取方塊類似,但會限制使用者只能從一組選項中選取一個選項。 - {@link android.widget.RadioGroup RadioGroup} + {@link android.widget.RadioGroup RadioGroup}
      {@link android.widget.RadioButton RadioButton} diff --git a/docs/html-intl/intl/zh-tw/guide/topics/ui/declaring-layout.jd b/docs/html-intl/intl/zh-tw/guide/topics/ui/declaring-layout.jd index 72755715e3a21..580ee230363a1 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/ui/declaring-layout.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/ui/declaring-layout.jd @@ -272,7 +272,7 @@ android.view.ViewGroup.LayoutParams} 的巢狀類別。這個子類別包含定 可定義檢視在螢幕中的實際大小 (描繪期間以及版面配置之後)。 這些值可能 (但未必) 會與寬度和高度測量值不同。 -您可以呼叫 +您可以呼叫 {@link android.view.View#getWidth()} 和 {@link android.view.View#getHeight()} 來取得尺寸描繪值。

      @@ -421,7 +421,7 @@ ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    17. 含有陣列中所有字串的 {@link android.widget.TextView} 的版面配置
    18. 字串陣列
    19. -

      接著,針對您的 {@link android.widget.ListView} 呼叫 +

      接著,針對您的 {@link android.widget.ListView} 呼叫 {@link android.widget.ListView#setAdapter setAdapter()}:

       ListView listView = (ListView) findViewById(R.id.listview);
      diff --git a/docs/html-intl/intl/zh-tw/guide/topics/ui/dialogs.jd b/docs/html-intl/intl/zh-tw/guide/topics/ui/dialogs.jd
      index b0ae12ea3a198..6e6db354ee77d 100644
      --- a/docs/html-intl/intl/zh-tw/guide/topics/ui/dialogs.jd
      +++ b/docs/html-intl/intl/zh-tw/guide/topics/ui/dialogs.jd
      @@ -32,7 +32,7 @@ page.tags=alertdialog,dialogfragment
             
    20. {@link android.app.DialogFragment}
    21. {@link android.app.AlertDialog}
    - +

    另請參閱

    1. 對話方塊設計指南
    2. @@ -248,7 +248,7 @@ AlertDialog dialog = builder.create();
      中立
      如果使用者不想繼續進行特定動作,但並非要取消動作,請使用這種按鈕。 這種按鈕會顯示在正面和負面按鈕之間。 -範例:[稍後提醒我] 按鈕。
      +範例:[稍後提醒我] 按鈕。

      您可以將以上其中一種按鈕加入 {@link @@ -320,7 +320,7 @@ android.app.AlertDialog.Builder#setAdapter setAdapter()} 指定清單。

      如要加入多重選項 (核取方塊) 或單一選項 (圓形按鈕),請使用 {@link android.app.AlertDialog.Builder#setMultiChoiceItems(Cursor,String,String, DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} 或 -{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()} 方法。

      @@ -346,7 +346,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { // If the user checked the item, add it to the selected items mSelectedItems.add(which); } else if (mSelectedItems.contains(which)) { - // Else, if the item is already in the array, remove it + // Else, if the item is already in the array, remove it mSelectedItems.remove(Integer.valueOf(which)); } } @@ -372,7 +372,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {

      雖然傳統清單和包含圓形按鈕的清單都可提供「單選」動作,但如果您想保留使用者的選擇,請使用 {@link -android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()}。也就是說,如果您想讓對話方塊再次開啟時顯示使用者目前所選的選項,請建立包含圓形按鈕的清單。 @@ -470,7 +470,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { public void onClick(DialogInterface dialog, int id) { LoginDialogFragment.this.getDialog().cancel(); } - }); + }); return builder.create(); } @@ -479,7 +479,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {

      提示:如果您想自訂對話方塊,請改為將 {@link android.app.Activity} 顯示為對話方塊,而不是使用 {@link android.app.Dialog} API。 方法很簡單,只要建立 Activity 然後在 {@code -<activity>} 宣示說明元素中將其主題設為 +<activity>} 宣示說明元素中將其主題設為 {@link android.R.style#Theme_Holo_Dialog Theme.Holo.Dialog} 即可:

      @@ -505,7 +505,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
       public class NoticeDialogFragment extends DialogFragment {
      -    
      +
           /* The activity that creates an instance of this dialog fragment must
            * implement this interface in order to receive event callbacks.
            * Each method passes the DialogFragment in case the host needs to query it. */
      @@ -513,10 +513,10 @@ public class NoticeDialogFragment extends DialogFragment {
               public void onDialogPositiveClick(DialogFragment dialog);
               public void onDialogNegativeClick(DialogFragment dialog);
           }
      -    
      +
           // Use this instance of the interface to deliver action events
           NoticeDialogListener mListener;
      -    
      +
           // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
           @Override
           public void onAttach(Activity activity) {
      @@ -543,7 +543,7 @@ public class NoticeDialogFragment extends DialogFragment {
       public class MainActivity extends FragmentActivity
                                 implements NoticeDialogFragment.NoticeDialogListener{
           ...
      -    
      +
           public void showNoticeDialog() {
               // Create an instance of the dialog fragment and show it
               DialogFragment dialog = new NoticeDialogFragment();
      @@ -656,7 +656,7 @@ public class CustomDialogFragment extends DialogFragment {
               // Inflate the layout to use as dialog or embedded fragment
               return inflater.inflate(R.layout.purchase_items, container, false);
           }
      -  
      +
           /** The system calls this only when creating the layout in a dialog. */
           @Override
           public Dialog onCreateDialog(Bundle savedInstanceState) {
      @@ -678,7 +678,7 @@ public class CustomDialogFragment extends DialogFragment {
       public void showDialog() {
           FragmentManager fragmentManager = getSupportFragmentManager();
           CustomDialogFragment newFragment = new CustomDialogFragment();
      -    
      +
           if (mIsLargeLayout) {
               // The device is using a large layout, so show the fragment as a dialog
               newFragment.show(fragmentManager, "dialog");
      diff --git a/docs/html-intl/intl/zh-tw/guide/topics/ui/menus.jd b/docs/html-intl/intl/zh-tw/guide/topics/ui/menus.jd
      index be1fa7f0dfdab..6f7405bc00eff 100644
      --- a/docs/html-intl/intl/zh-tw/guide/topics/ui/menus.jd
      +++ b/docs/html-intl/intl/zh-tw/guide/topics/ui/menus.jd
      @@ -83,9 +83,9 @@ parent.link=index.html
       

      請參閱建立選項選單

      - +
      內容選單和內容關聯動作模式
      - +
      內容選單是會在使用者長按某元素時顯示的浮動選單。 它提供的動作會影響所選取內容或內容畫面。 @@ -94,7 +94,7 @@ parent.link=index.html

      請參閱建立內容關聯選單

      - +
      彈出式選單
      彈出式選單顯示的項目清單會以垂直清單的方式,錨定在呼叫該選單的檢視。 它很適合用來提供與特定內容有關的動作溢出,或針對第二部分的命令提供選項。 @@ -135,7 +135,7 @@ parent.link=index.html
      <item>
      建立代表選單中單一項目的 {@link android.view.MenuItem}。此元素可以包含巢狀 <menu> 元素以建立子選單。
      - +
      <group>
      可供 {@code <item>} 元素選用的不可見容器。它可讓您將選單項目分類,以便分享屬性,例如有效狀態與可見度。 如需詳細資訊,請參閱建立選單群組。 @@ -742,8 +742,8 @@ android.widget.PopupMenu#getMenu() PopupMenu.getMenu()} 所傳回的 {@link andr
       <ImageButton
      -    android:layout_width="wrap_content" 
      -    android:layout_height="wrap_content" 
      +    android:layout_width="wrap_content"
      +    android:layout_height="wrap_content"
           android:src="@drawable/ic_overflow_holo_dark"
           android:contentDescription="@string/descr_overflow_button"
           android:onClick="showPopup" />
      @@ -900,7 +900,7 @@ android.view.MenuItem#setChecked(boolean) setChecked()} 方法在程式碼中變
       

      已選取可勾選項目時,系統會呼叫所選取個別項目的回呼方法 (例如 {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()})。 您必須在這裡設定核取方塊的狀態,原因是核取方塊或選項按鈕並不會自動變更其狀態。 -您可以利用 +您可以利用 {@link android.view.MenuItem#isChecked()} 來查詢項目的目前狀態 (使用者選取它之前的狀態),然後利用 {@link android.view.MenuItem#setChecked(boolean) setChecked()} 來設定勾選狀態。例如:

      @@ -1010,7 +1010,7 @@ addIntentOptions()} 時,它會覆寫第一個引數中所指定選單群組中

      您也能向其他應用程式提供 Activity 的服務,這樣即可在其他應用程式的選單中包含您的應用程式 (與上述的角色顛倒)。

      -

      如要包含在其他應用程式選單中,您必須照常定義意圖篩選器,但務必為意圖篩選器類別納入 +

      如要包含在其他應用程式選單中,您必須照常定義意圖篩選器,但務必為意圖篩選器類別納入 {@link android.content.Intent#CATEGORY_ALTERNATIVE} 和/或 {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} 值。 例如:

      diff --git a/docs/html-intl/intl/zh-tw/guide/topics/ui/notifiers/notifications.jd b/docs/html-intl/intl/zh-tw/guide/topics/ui/notifiers/notifications.jd index b8537445cff01..d7bf469978537 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/ui/notifiers/notifications.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/ui/notifiers/notifications.jd @@ -81,7 +81,7 @@ page.title=通知 圖 2.通知匣中的通知。

      -

      注意:除非另外註明,否則本指南參照支援程式庫 4 版中的 +

      注意:除非另外註明,否則本指南參照支援程式庫 4 版中的 {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder} 類別。類別 {@link android.app.Notification.Builder Notification.Builder} 是在 Android 3.0 (API 級別 11) 新增。 @@ -97,10 +97,10 @@ page.title=通知

      建立通知

      -

      您會為 +

      您會為 {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder} 物件中的通知指定 UI 資訊與動作。 -如要建立通知本身,您可以呼叫 -{@link android.support.v4.app.NotificationCompat.Builder#build NotificationCompat.Builder.build()},其傳回的 +如要建立通知本身,您可以呼叫 +{@link android.support.v4.app.NotificationCompat.Builder#build NotificationCompat.Builder.build()},其傳回的 {@link android.app.Notification} 物件會包含您的規格。如要發出通知,您可以呼叫 {@link android.app.NotificationManager#notify NotificationManager.notify()} 將 {@link android.app.Notification} 物件傳送至系統。

      @@ -149,7 +149,7 @@ page.title=通知 在 {@link android.app.Notification} 內,動作本身是由 {@link android.app.PendingIntent} 完成定義,其中包含的 {@link android.content.Intent} 會啟動您應用程式中的 -{@link android.app.Activity}。如要將 +{@link android.app.Activity}。如要將 {@link android.app.PendingIntent} 與手勢關聯,可呼叫 {@link android.support.v4.app.NotificationCompat.Builder} 的適當方法。例如,如果當使用者按一下通知匣中的通知文字時,您希望啟動 {@link android.app.Activity},可呼叫 @@ -394,7 +394,7 @@ numMessages = 0;

      啟動 Activity 時保留導覽

      當您從通知啟動 {@link android.app.Activity} 時,您必須保留使用者預期的導覽體驗。 -按一下 [返回] 應可將使用者從應用程式的一般工作流程帶回主螢幕,而按一下 +按一下 [返回] 應可將使用者從應用程式的一般工作流程帶回主螢幕,而按一下 [近期記錄] 應會將 {@link android.app.Activity} 顯示為個別的工作。如要保留導覽體驗,請以全新的工作啟動 {@link android.app.Activity}。您該如何設定 @@ -466,7 +466,7 @@ numMessages = 0;

    3. - 此外您還需要新增 Android 4.1 以上版本的支援。為此,請將 + 此外您還需要新增 Android 4.1 以上版本的支援。為此,請將 android:parentActivityName 屬性新增到您要啟動 {@link android.app.Activity} 的 <activity> 元素。 @@ -722,7 +722,7 @@ setProgress(max, progress, false)} 將該列新增至您的通知,然後發出

      當操作完成時,您可以繼續顯示進度列或將其移除。不論是任何一種情況,都務必更新通知文字來指出操作已完成。 - 如要移除進度列,請呼叫 + 如要移除進度列,請呼叫 {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress(0, 0, false)}。例如:

      @@ -933,7 +933,7 @@ Notification notification = new Notification.Builder(context)

      - 如要定義自訂通知版面配置,請從具現化可擴大 XML 配置檔案的 + 如要定義自訂通知版面配置,請從具現化可擴大 XML 配置檔案的 {@link android.widget.RemoteViews} 物件著手。接著,改為呼叫 {@link android.support.v4.app.NotificationCompat.Builder#setContent setContent()},而不是呼叫像是 {@link android.support.v4.app.NotificationCompat.Builder#setContentTitle setContentTitle()} 的方法。 diff --git a/docs/html-intl/intl/zh-tw/guide/topics/ui/overview.jd b/docs/html-intl/intl/zh-tw/guide/topics/ui/overview.jd index 44d05a82ebc2e..0ac4002cf424a 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/ui/overview.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/ui/overview.jd @@ -39,7 +39,7 @@ XML 提供類似於 HTML 且人類看得懂的版面配置結構。

       <?xml version="1.0" encoding="utf-8"?>
       <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -              android:layout_width="fill_parent" 
      +              android:layout_width="fill_parent"
                     android:layout_height="fill_parent"
                     android:orientation="vertical" >
           <TextView android:id="@+id/text"
      @@ -60,7 +60,7 @@ XML 提供類似於 HTML 且人類看得懂的版面配置結構。

      如需建立 UI 版面配置的完整指南,請參閱 XML 版面配置。 - +

      使用者介面元件

      您不必使用 {@link android.view.View} 與 {@link diff --git a/docs/html-intl/intl/zh-tw/guide/topics/ui/settings.jd b/docs/html-intl/intl/zh-tw/guide/topics/ui/settings.jd index 91ac929e0fa12..7a7ff9b7973c9 100644 --- a/docs/html-intl/intl/zh-tw/guide/topics/ui/settings.jd +++ b/docs/html-intl/intl/zh-tw/guide/topics/ui/settings.jd @@ -226,7 +226,7 @@ android.preference.ListPreference}。這兩個項目都包含下列三個屬性

      {@code android:key}
      需要這個屬性才能保留資料值的偏好設定。它會指定當系統將此設定值儲存於 {@link android.content.SharedPreferences} 時要使用的唯一索引鍵 (字串)。 - +

      只有在下列情況下不需要此屬性:偏好設定為 {@link android.preference.PreferenceCategory} 或 {@link android.preference.PreferenceScreen},或者偏好設定指定 {@link android.content.Intent} 進行呼叫 (搭配 {@code <intent>} 元素) 或 {@link android.app.Fragment} 進行顯示 (搭配 {@code android:fragment} 屬性)。 @@ -285,7 +285,7 @@ android.preference.PreferenceCategory}。

       <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
      -    <PreferenceCategory 
      +    <PreferenceCategory
               android:title="@string/pref_sms_storage_title"
               android:key="pref_key_storage_settings">
               <CheckBoxPreference
      @@ -293,12 +293,12 @@ android.preference.PreferenceCategory}。
                   android:summary="@string/pref_summary_auto_delete"
                   android:title="@string/pref_title_auto_delete"
                   android:defaultValue="false"... />
      -        <Preference 
      +        <Preference
                   android:key="pref_key_sms_delete_limit"
                   android:dependency="pref_key_auto_delete"
                   android:summary="@string/pref_summary_delete_limit"
                   android:title="@string/pref_title_sms_delete"... />
      -        <Preference 
      +        <Preference
                   android:key="pref_key_mms_delete_limit"
                   android:dependency="pref_key_auto_delete"
                   android:summary="@string/pref_summary_delete_limit"
      @@ -588,11 +588,11 @@ android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} 回呼以
       
       <?xml version="1.0" encoding="utf-8"?>
       <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
      -    <header 
      +    <header
               android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentOne"
               android:title="@string/prefs_category_one"
               android:summary="@string/prefs_summ_category_one" />
      -    <header 
      +    <header
               android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentTwo"
               android:title="@string/prefs_category_two"
               android:summary="@string/prefs_summ_category_two" >
      @@ -672,15 +672,15 @@ android.preference.Preference <Preference>} 元素會傳送一個 {@link a
       

      例如,下列為使用 Android 3.0及更新版本的偏好設定標頭 XML 檔案 ({@code res/xml/preference_headers.xml}): -

      +

       <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
      -    <header 
      +    <header
               android:fragment="com.example.prefs.SettingsFragmentOne"
               android:title="@string/prefs_category_one"
               android:summary="@string/prefs_summ_category_one" />
      -    <header 
      +    <header
               android:fragment="com.example.prefs.SettingsFragmentTwo"
               android:title="@string/prefs_category_two"
               android:summary="@string/prefs_summ_category_two" />
      @@ -692,18 +692,18 @@ android.preference.Preference <Preference>} 元素會傳送一個 {@link a
       
       
       <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
      -    <Preference 
      +    <Preference
               android:title="@string/prefs_category_one"
               android:summary="@string/prefs_summ_category_one"  >
      -        <intent 
      +        <intent
                   android:targetPackage="com.example.prefs"
                   android:targetClass="com.example.prefs.SettingsActivity"
                   android:action="com.example.prefs.PREFS_ONE" />
           </Preference>
      -    <Preference 
      +    <Preference
               android:title="@string/prefs_category_two"
               android:summary="@string/prefs_summ_category_two" >
      -        <intent 
      +        <intent
                   android:targetPackage="com.example.prefs"
                   android:targetClass="com.example.prefs.SettingsActivity"
                   android:action="com.example.prefs.PREFS_TWO" />
      @@ -975,11 +975,11 @@ android.preference.DialogPreference} 的建構函式,該偏好設定宣告版
       public class NumberPickerPreference extends DialogPreference {
           public NumberPickerPreference(Context context, AttributeSet attrs) {
               super(context, attrs);
      -        
      +
               setDialogLayoutResource(R.layout.numberpicker_dialog);
               setPositiveButtonText(android.R.string.ok);
               setNegativeButtonText(android.R.string.cancel);
      -        
      +
               setDialogIcon(null);
           }
           ...
      @@ -1194,7 +1194,7 @@ protected void onRestoreInstanceState(Parcelable state) {
           // Cast state to custom BaseSavedState and pass to superclass
           SavedState myState = (SavedState) state;
           super.onRestoreInstanceState(myState.getSuperState());
      -    
      +
           // Set this Preference's widget to reflect the restored state
           mNumberPicker.setValue(myState.value);
       }
      diff --git a/docs/html-intl/intl/zh-tw/guide/topics/ui/ui-events.jd b/docs/html-intl/intl/zh-tw/guide/topics/ui/ui-events.jd
      index 68714e8b2b591..8e009e0d3bea0 100644
      --- a/docs/html-intl/intl/zh-tw/guide/topics/ui/ui-events.jd
      +++ b/docs/html-intl/intl/zh-tw/guide/topics/ui/ui-events.jd
      @@ -187,7 +187,7 @@ android.app.Activity} 能在發送至視窗之前攔截所有輕觸事件。
    4. - 這讓 {@link android.view.ViewGroup} 在發送至子檢視時能監控事件。
    5. {@link android.view.ViewParent#requestDisallowInterceptTouchEvent(boolean) - ViewParent.requestDisallowInterceptTouchEvent(boolean)} - 呼叫這個父檢視以指出不應該使用 {@link + ViewParent.requestDisallowInterceptTouchEvent(boolean)} - 呼叫這個父檢視以指出不應該使用 {@link android.view.ViewGroup#onInterceptTouchEvent(MotionEvent)} 攔截輕觸事件。
    6. @@ -199,11 +199,11 @@ android.view.ViewGroup} 在發送至子檢視時能監控事件。 不過,如果裝置具有輕觸功能,而且使用者透過輕觸方式開始與介面互動,就不需要再將項目反白顯示,或是對特定檢視提供焦點。 因此,這就是名稱為「輕觸模式」的互動模式。 - +

      如果是具備輕觸功能的裝置,使用者輕觸螢幕之後,裝置就會進入輕觸模式。 -從這點以此類推,只有 +從這點以此類推,只有 {@link android.view.View#isFocusableInTouchMode} 為 true 的檢視才可設定焦點,例如文字編輯小工具。 其他可輕觸的檢視,例如按鈕,在輕觸時不會成為焦點;按下時,只會觸發 on-click 接聽器。 @@ -214,7 +214,7 @@ android.view.ViewGroup} 在發送至子檢視時能監控事件。

      -整個系統 (所有視窗和 Activity) 都會保留輕觸模式的狀態。如要查詢目前的狀態,您可以呼叫 +整個系統 (所有視窗和 Activity) 都會保留輕觸模式的狀態。如要查詢目前的狀態,您可以呼叫 {@link android.view.View#isInTouchMode} 以查看裝置目前是否處於輕觸模式。

      @@ -282,7 +282,7 @@ android.view.ViewGroup} 在發送至子檢視時能監控事件。 the framework will take care of measuring, laying out, and drawing the tree as appropriate.
    - +

    Note: The entire View tree is single threaded. You must always be on the UI thread when calling any method on any View. If you are doing work on other threads and want to update the state of a View diff --git a/docs/html-intl/intl/zh-tw/preview/api-overview.jd b/docs/html-intl/intl/zh-tw/preview/api-overview.jd index aeace5bdddb2f..e5fdf8d6d61b1 100644 --- a/docs/html-intl/intl/zh-tw/preview/api-overview.jd +++ b/docs/html-intl/intl/zh-tw/preview/api-overview.jd @@ -414,7 +414,7 @@ android.os.PowerManager.WakeLock}, {@link android.app.AlarmManager} 鬧鐘和 GP - +

    diff --git a/docs/html-intl/intl/zh-tw/preview/features/background-optimization.jd b/docs/html-intl/intl/zh-tw/preview/features/background-optimization.jd index d0883810fed0c..123498b08b897 100644 --- a/docs/html-intl/intl/zh-tw/preview/features/background-optimization.jd +++ b/docs/html-intl/intl/zh-tw/preview/features/background-optimization.jd @@ -88,7 +88,7 @@ page.image=images/cards/card-nyc_2x.jpg

    - 在此文件中,我們將學習如何使用替代方法 (例如 + 在此文件中,我們將學習如何使用替代方法 (例如 {@link android.app.job.JobScheduler}) 改寫您的應用程式以配合這些新的限制。

    diff --git a/docs/html-intl/intl/zh-tw/preview/features/direct-boot.jd b/docs/html-intl/intl/zh-tw/preview/features/direct-boot.jd index a42ec11b940df..7e4ea732b244e 100644 --- a/docs/html-intl/intl/zh-tw/preview/features/direct-boot.jd +++ b/docs/html-intl/intl/zh-tw/preview/features/direct-boot.jd @@ -87,7 +87,7 @@ page.image=images/cards/card-nyc_2x.jpg

    存取裝置加密的儲存空間

    如果要存取裝置加密的儲存空間,請透過呼叫 -Context.createDeviceEncryptedStorageContext() 以建立第二個 +Context.createDeviceEncryptedStorageContext() 以建立第二個 {@link android.content.Context} 實例。使用此內容建立的所有儲存 API 呼叫都可以存取裝置加密的儲存空間。 下列範例會存取裝置加密的儲存空間並開啟現有的應用程式資料檔案: diff --git a/docs/html-intl/intl/zh-tw/preview/features/multi-window.jd b/docs/html-intl/intl/zh-tw/preview/features/multi-window.jd index 788951c8fb984..5ea247bd4b5ed 100644 --- a/docs/html-intl/intl/zh-tw/preview/features/multi-window.jd +++ b/docs/html-intl/intl/zh-tw/preview/features/multi-window.jd @@ -170,7 +170,7 @@ page.keywords="multi-window", "android N", "split screen", "free-form"

    android:resizeableActivity

    - 在宣示說明的 <activity> 或 + 在宣示說明的 <activity><application> 節點中,設定此屬性以啟用或停用多視窗顯示:

    diff --git a/docs/html-intl/intl/zh-tw/preview/features/picture-in-picture.jd b/docs/html-intl/intl/zh-tw/preview/features/picture-in-picture.jd index b0ee8b8360cbb..6b8a17805fa59 100644 --- a/docs/html-intl/intl/zh-tw/preview/features/picture-in-picture.jd +++ b/docs/html-intl/intl/zh-tw/preview/features/picture-in-picture.jd @@ -150,7 +150,7 @@ public void onPictureInPictureChanged(boolean inPictureInPicture) {

    當您的活動切換到 PIP 時,系統會將活動視為暫停狀態並呼叫您活動的 onPause() 方法。 影片播放不應該暫停,而且活動因為 PIP 模式而暫停時,影片應該繼續播放。 -查看您活動的 +查看您活動的 onPause() 方法中的 PIP 並適當地處理播放,例如:

    diff --git a/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/index.jd b/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/index.jd index 4225184c80211..acee1d421fc49 100644 --- a/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/index.jd +++ b/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/index.jd @@ -55,7 +55,7 @@ android.app.Activity} 執行個體都會接收的生命週期重要回呼方法

    課程

    - +
    啟動應用行為顯示
    了解應用行為顯示生命週期的有關基本概念、使用者啟動應用程式的方式,以及建立基本應用行為顯示的執行方式。 @@ -68,5 +68,5 @@ android.app.Activity} 執行個體都會接收的生命週期重要回呼方法
    重新建立應用行為顯示
    了解在應用行為顯示遭終結時的狀況,以及如何在需要時重新建置應用行為顯示狀態。
    -
    + diff --git a/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/pausing.jd b/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/pausing.jd index 8c0843da6a3a2..f47768a68c9dd 100644 --- a/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/pausing.jd +++ b/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/pausing.jd @@ -8,13 +8,13 @@ trainingnavtop=true
    - +

    本課程示範

    1. 暫停您的應用行為顯示
    2. 繼續您的應用行為顯示
    - +

    您也應該閱讀

    • 應用行為顯示 @@ -59,7 +59,7 @@ android.app.Activity#onPause()} 的呼叫,可能表示該應用行為顯示將

      暫停您的應用行為顯示

      - +

      若系統為您的應用行為顯示呼叫 {@link android.app.Activity#onPause()},嚴格來說意味著您的應用行為顯示仍是部分可見,但多數情況下表示使用者離開應用行為顯示,該應用行為顯示很快將進入「已停止」狀態。 通常,您應使用 {@link android.app.Activity#onPause()} 回呼執行以下操作: diff --git a/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/recreating.jd b/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/recreating.jd index 4b0efdaa3d850..ad23786584f56 100644 --- a/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/recreating.jd +++ b/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/recreating.jd @@ -8,13 +8,13 @@ trainingnavtop=true

      - +

      本課程示範

      1. 儲存您的應用行為顯示狀態
      2. 還原您的應用行為顯示狀態
      - +

      您也應該閱讀

      • 支援不同的螢幕 @@ -105,7 +105,7 @@ public void onSaveInstanceState(Bundle savedInstanceState) { // Save the user's current game state savedInstanceState.putInt(STATE_SCORE, mCurrentScore); savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel); - + // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); } @@ -138,7 +138,7 @@ onCreate()} 中還原某些狀態資料:

        @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Always call the superclass first - + // Check whether we're recreating a previously destroyed instance if (savedInstanceState != null) { // Restore value of members from saved state @@ -157,12 +157,12 @@ android.app.Activity#onRestoreInstanceState onRestoreInstanceState()},系統 只有存在要還原的已儲存狀態時,系統才會呼叫 {@link android.app.Activity#onRestoreInstanceState onRestoreInstanceState()},因此您無需檢查 {@link android.os.Bundle} 是否為 null:

        - +
         public void onRestoreInstanceState(Bundle savedInstanceState) {
             // Always call the superclass so it can restore the view hierarchy
             super.onRestoreInstanceState(savedInstanceState);
        -   
        +
             // Restore state members from saved instance
             mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
             mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
        diff --git a/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/starting.jd b/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/starting.jd
        index fae2fa35091d3..b03f22be92005 100644
        --- a/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/starting.jd
        +++ b/docs/html-intl/intl/zh-tw/training/basics/activity-lifecycle/starting.jd
        @@ -9,7 +9,7 @@ trainingnavtop=true
         
         
        - +

        本課程示範

        1. 了解生命週期回呼
        2. @@ -17,7 +17,7 @@ trainingnavtop=true
        3. 建立新執行個體
        4. 終結應用行為顯示
        - +

        您也應該閱讀

        @@ -53,7 +53,7 @@ This page provides an overview of some new features and technologies.


        Quick Search Box
        - +

        New Camera/Camcorder UI @@ -67,32 +67,32 @@ Battery Usage Indicator

        Quick Search Box for Android

        -

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

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

        -

        The system constantly learns which search results are more relevant based on what is -clicked. So popular contacts or apps that have previously been picked will bubble up to +

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

        -

        The search framework also provides developers a way to easily expose relevant +

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

        Camera, Camcorder, and Gallery

        -

        An updated user interface provides an integrated camera, camcorder, and gallery experience. -Users can quickly toggle between still and video capture modes. Additionally, the gallery +

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

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

        VPN, 802.1x

        -

        A new Virtual Private Network (VPN) control panel in Settings allows users +

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

          @@ -105,8 +105,8 @@ to configure and connect to the following types of VPNs:

          Battery usage indicator

          -

          A new battery usage screen lets users see which apps and services are consuming -battery power. If the user determines that a particular service or application is +

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

          @@ -132,11 +132,11 @@ it easier for users to discover great apps and games from developers.

          • At the homescreen, users can choose among Apps, Games, and Downloads.
          • Inside a category, users can explore titles that are Top paid, Top free, and Just in.
          • -
          • For each title, users can now see screenshots submitted by developers in addition to +
          • For each title, users can now see screenshots submitted by developers in addition to reviews from other users.
          - - + +

          New Platform Technologies

          @@ -145,44 +145,44 @@ it easier for users to discover great apps and games from developers.

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

          Text-to-speech engine

          -

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

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

          Gestures

          -

          A new gestures framework provides application developers with a framework for creating, storing, +

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

          -

          Developers can use the new GestureBuilder tool included in the Android 1.6 SDK to generate libraries +

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

          Accessibility

          -

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

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

          Expanded support for screen densities and resolutions

          -

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

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

          @@ -208,7 +208,7 @@ application.

          New Framework APIs

          -

          For a detailed overview of new APIs, see the -Version Notes. -For a complete report of all API changes, see the +

          For a detailed overview of new APIs, see the +Version Notes. +For a complete report of all API changes, see the API Differences Report. diff --git a/docs/html/about/versions/android-2.0-highlights.jd b/docs/html/about/versions/android-2.0-highlights.jd index c16088ad8021b..3f7e1c8cd2386 100644 --- a/docs/html/about/versions/android-2.0-highlights.jd +++ b/docs/html/about/versions/android-2.0-highlights.jd @@ -33,7 +33,7 @@ sdk.date=October 2009 -

        @@ -49,7 +49,7 @@ and technologies in Android 2.0.

      - +

      New User Features

      @@ -99,10 +99,10 @@ when you touch a contact photo or status icon.
    • @@ -150,7 +150,7 @@ when you touch a contact photo or status icon.

      Browser

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

    -

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

    +

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

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

    diff --git a/docs/html/about/versions/android-3.0.jd b/docs/html/about/versions/android-3.0.jd index 51847433f50ac..3175d3ca3afad 100644 --- a/docs/html/about/versions/android-3.0.jd +++ b/docs/html/about/versions/android-3.0.jd @@ -392,7 +392,7 @@ Demos application.

    Extended UI framework

      - +
    • Multiple-choice selection for ListView and GridView

      New {@link android.widget.AbsListView#CHOICE_MODE_MULTIPLE_MODAL} mode for {@link @@ -419,9 +419,9 @@ java class in the API Demos sample application.

    • - +
    • New APIs to transform views - +

      New APIs allow you to easily apply 2D and 3D transformations to views in your activity layout. New transformations are made possible with a set of object properties that define the view's layout position, orientation, transparency and more.

      @@ -452,7 +452,7 @@ animator.start();
    • - +
    • New holographic themes

      The standard system widgets and overall look have been redesigned and incorporate a new @@ -475,55 +475,55 @@ href="{@docRoot}guide/topics/ui/themes.html#SelectATheme">select a theme based o version.

    • - - + +
    • New widgets
      • {@link android.widget.AdapterViewAnimator}

        Base class for an {@link android.widget.AdapterView} that performs animations when switching between its views.

      • - +
      • {@link android.widget.AdapterViewFlipper}

        Simple {@link android.widget.ViewAnimator} that animates between two or more views that have been added to it. Only one child is shown at a time. If requested, it can automatically flip between each child at a regular interval.

      • - +
      • {@link android.widget.CalendarView}

        Allows users to select dates from a calendar by touching the date and can scroll or fling the calendar to a desired date. You can configure the range of dates available in the widget.

      • - +
      • {@link android.widget.ListPopupWindow}

        Anchors itself to a host view and displays a list of choices, such as for a list of suggestions when typing into an {@link android.widget.EditText} view.

      • - +
      • {@link android.widget.NumberPicker}

        Enables the user to select a number from a predefined range. The widget presents an input field and up and down buttons for selecting a number. Touching the input field allows the user to scroll through values or touch again to directly edit the current value. It also allows you to map positions to strings, so that the corresponding string is displayed instead of the index position.

      • - +
      • {@link android.widget.PopupMenu}

        Displays a {@link android.view.Menu} in a modal popup window that's anchored to a view. The popup appears below the anchor view if there is room, or above it if there is not. If the IME (soft keyboard) is visible, the popup does not overlap the IME it until the user touches the menu.

      • - +
      • {@link android.widget.SearchView}

        Provides a search box that you can configure to deliver search queries to a specified activity and display search suggestions (in the same manner as the traditional search dialog). This widget is particularly useful for offering a search widget in the Action Bar. For more information, see Creating a Search Interface.

      • - +
      • {@link android.widget.StackView}

        A view that displays its children in a 3D stack and allows users to swipe through views like a rolodex.

      • - +
    • - +
    @@ -545,7 +545,7 @@ smoother scrolling, and overall better performance and response to user interact
  • View support for hardware and software layers - +

    By default, a {@link android.view.View} has no layer specified. You can specify that the view be backed by either a hardware or software layer, specified by values {@link android.view.View#LAYER_TYPE_HARDWARE} and {@link android.view.View#LAYER_TYPE_SOFTWARE}, using @@ -563,7 +563,7 @@ software layer, which can potentially be slow.

    For more information, see the {@link android.view.View#LAYER_TYPE_HARDWARE} and {@link android.view.View#LAYER_TYPE_SOFTWARE} documentation.

  • - +
  • Renderscript 3D graphics engine @@ -591,7 +591,7 @@ android.media.MediaRecorder#setCaptureRate setCaptureRate()} sets the rate at wh should be captured.

  • Texture support for image streams - +

    New {@link android.graphics.SurfaceTexture} allows you to capture an image stream as an OpenGL ES texture. By calling {@link android.hardware.Camera#setPreviewTexture setPreviewTexture()} for your {@link android.hardware.Camera} instance, you can specify the {@link @@ -599,7 +599,7 @@ android.graphics.SurfaceTexture} upon which to draw video playback or preview fr camera.

  • HTTP Live streaming - +

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

  • EXIF data - +

    The {@link android.media.ExifInterface} includes new fields for photo aperture, ISO, and exposure time.

  • @@ -810,7 +810,7 @@ expressed with acceleration and rotation rate data. A web page can register for events by calling {@code window.addEventListener} with event type {@code "deviceorientation"} and register for motion events by registering the {@code "devicemotion"} event type.

    - +
  • CSS 3D Transforms

    As defined by the CSS 3D Transform Module specification, the Browser allows elements rendered by CSS to be transformed in three @@ -967,7 +967,7 @@ the system, prior to installing the application.

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need compile the application against the Android library that is provided in -the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might +the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" attribute to the <uses-sdk> element in the application's manifest. If your application is designed to run only on Android 2.3 and higher, diff --git a/docs/html/about/versions/android-3.1-highlights.jd b/docs/html/about/versions/android-3.1-highlights.jd index 5283c2a458615..2a706989f4719 100644 --- a/docs/html/about/versions/android-3.1-highlights.jd +++ b/docs/html/about/versions/android-3.1-highlights.jd @@ -93,7 +93,7 @@ device.

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

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

    Calendar

    diff --git a/docs/html/about/versions/android-3.1.jd b/docs/html/about/versions/android-3.1.jd index cdcf51eee6294..e1486bef7da82 100644 --- a/docs/html/about/versions/android-3.1.jd +++ b/docs/html/about/versions/android-3.1.jd @@ -240,7 +240,7 @@ and game controllers include android.view.MotionEvent#AXIS_HAT_Y}, {@link android.view.MotionEvent#AXIS_RTRIGGER}, {@link android.view.MotionEvent#AXIS_ORIENTATION}, {@link -android.view.MotionEvent#AXIS_THROTTLE}, and many others. +android.view.MotionEvent#AXIS_THROTTLE}, and many others. Existing {@link android.view.MotionEvent} axes are represented by {@link android.view.MotionEvent#AXIS_X}, {@link android.view.MotionEvent#AXIS_Y}, {@link android.view.MotionEvent#AXIS_PRESSURE}, {@link @@ -299,7 +299,7 @@ each axis value.

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

    To look at a sample application that uses joystick motion events, see GameControllerInput +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/GameControllerInput.html">GameControllerInput and GameView.

    diff --git a/docs/html/about/versions/android-3.2.jd b/docs/html/about/versions/android-3.2.jd index 887755cfefb2e..c6df7f5ddab60 100644 --- a/docs/html/about/versions/android-3.2.jd +++ b/docs/html/about/versions/android-3.2.jd @@ -132,7 +132,7 @@ provides these tools:

    • New resource qualifiers for targeting layouts and other resources to a -minimum smallestWidth, width, or height, and
    • +minimum smallestWidth, width, or height, and
    • New manifest attributes, for specifying the app's maximum screen compatibility range
    @@ -201,7 +201,7 @@ the resource should be used, measured in "dp" units. As mentioned above, a screen's smallestWidth is constant, regardless of orientation. Examples: sw320dp, sw720dp, sw720dp.
  • -
  • wNNNdp and hNNNdp — Specifies the minimum +
  • wNNNdp and hNNNdp — Specifies the minimum width or height on which the resource should be used, measured in "dp" units. As mentioned above, a screen's width and height are relative to the orientation of the screen and change whenever the orientation changes. Examples: @@ -214,7 +214,7 @@ dp, others for wider than 600 dp, and others for wider than 720 dp. When multiple resource configurations are qualified for a given screen, the system selects the configuration that is the closest match. For precise control over which resources are loaded on a given screen, you can tag resources with one -qualifier or combine several new or existing qualifiers. +qualifier or combine several new or existing qualifiers.

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

    diff --git a/docs/html/about/versions/android-4.0.3.jd b/docs/html/about/versions/android-4.0.3.jd index 3be684df63b27..bcfa35c94bce8 100644 --- a/docs/html/about/versions/android-4.0.3.jd +++ b/docs/html/about/versions/android-4.0.3.jd @@ -102,16 +102,16 @@ android:name="android.permission.WRITE_SOCIAL_STREAM"> in their manife
  • Adds the class {@link android.provider.CalendarContract.Colors} to represent a color table in the Calendar Provider. The class provides fields for accessing -colors available for a given account. Colors are referenced by +colors available for a given account. Colors are referenced by {@link android.provider.CalendarContract.ColorsColumns#COLOR_KEY COLOR_KEY} which must be unique for a given account name/type. These values can only be updated by the sync adapter.
  • Adds {@link android.provider.CalendarContract.CalendarColumns#ALLOWED_AVAILABILITY ALLOWED_AVAILABILITY} -and +and {@link android.provider.CalendarContract.CalendarColumns#ALLOWED_ATTENDEE_TYPES ALLOWED_ATTENDEE_TYPES} for exchange/sync support.
  • Adds {@link android.provider.CalendarContract.AttendeesColumns#TYPE_RESOURCE} -(such as conference rooms) for attendees and +(such as conference rooms) for attendees and {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY_TENTATIVE}, as well as {@link android.provider.CalendarContract.EventsColumns#EVENT_COLOR_KEY} for events.
  • @@ -123,7 +123,7 @@ for events. own padding. Instead, the system now automatically adds padding for each widget, based the characteristics of the current screen. This leads to a more uniform, consistent presentation of widgets in a grid. To assist applications that host -home screen widgets, the platform provides a new method +home screen widgets, the platform provides a new method {@link android.appwidget.AppWidgetHostView#getDefaultPaddingForWidget(android.content.Context, android.content.ComponentName, android.graphics.Rect) getDefaultPaddingForWidget()}. Applications can call this method to get the system-defined padding and account for it when computing the number of cells to @@ -136,7 +136,7 @@ allocate to the widget.

    android.view.textservice.SpellCheckerSession#cancel() cancel()} method cancels any pending and running spell-checker tasks in a session. -
  • For spell-checker services, a new suggestions flag, +
  • For spell-checker services, a new suggestions flag, {@link android.view.textservice.SuggestionsInfo#RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS}, lets the services distinguish higher-confidence suggestions from lower-confidence ones. For example, a spell-checker could set the flag if an @@ -206,8 +206,8 @@ the inflated layout.
  • allow apps to get and set the maximum scroll offset for an {@link android.view.accessibility.AccessibilityRecord} object. -
  • When touch-exploration mode is enabled, a new secure setting -{@link android.provider.Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD} +
  • When touch-exploration mode is enabled, a new secure setting +{@link android.provider.Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD} indicates whether the user requests the IME to speak text entered in password fields, even when a headset is not in use. By default, no password text is spoken unless a headset is in use.
  • diff --git a/docs/html/about/versions/android-4.0.jd b/docs/html/about/versions/android-4.0.jd index 43185827b4f6e..48afcd48164f8 100644 --- a/docs/html/about/versions/android-4.0.jd +++ b/docs/html/about/versions/android-4.0.jd @@ -99,7 +99,7 @@ device.

    User Profile

    Android now includes a personal profile that represents the device owner, as defined by the -{@link android.provider.ContactsContract.Profile} table. Social apps that maintain a user identity +{@link android.provider.ContactsContract.Profile} table. Social apps that maintain a user identity can contribute to the user's profile data by creating a new {@link android.provider.ContactsContract.RawContacts} entry within the {@link android.provider.ContactsContract.Profile}. That is, raw contacts that represent the device user do @@ -210,7 +210,7 @@ used by the sync adapter. The provider takes no action with items in this table them when their related events are deleted. -

    To access a user’s calendar data with the Calendar Provider, your application must request +

    To access a user’s calendar data with the Calendar Provider, your application must request the {@link android.Manifest.permission#READ_CALENDAR} permission (for read access) and {@link android.Manifest.permission#WRITE_CALENDAR} (for write access).

    @@ -850,7 +850,7 @@ android.view.accessibility.AccessibilityRecord} (there may be several records at event).
  • From either {@link android.view.accessibility.AccessibilityEvent} or an individual {@link -android.view.accessibility.AccessibilityRecord}, you can call {@link +android.view.accessibility.AccessibilityRecord}, you can call {@link android.view.accessibility.AccessibilityRecord#getSource() getSource()} to retrieve a {@link android.view.accessibility.AccessibilityNodeInfo} object.

    An {@link android.view.accessibility.AccessibilityNodeInfo} represents a single node diff --git a/docs/html/about/versions/android-4.1.jd b/docs/html/about/versions/android-4.1.jd index 4131c36fe1ca8..4d7cb85f43351 100644 --- a/docs/html/about/versions/android-4.1.jd +++ b/docs/html/about/versions/android-4.1.jd @@ -103,8 +103,8 @@ useful new APIs for app developers.

    Make sure that your app works well on a variety of screens: offering good, - crisp graphics and appropriate layouts on low resolution and physically small - screens. Ensure that your app is designed to be easily localized by - accommodating the variations between languages: allow for spacing, density, - order, emphasis, and wording variations. Also make sure that date, time, and - the like are internationalized and displayed according to the phone’s + crisp graphics and appropriate layouts on low resolution and physically small + screens. Ensure that your app is designed to be easily localized by + accommodating the variations between languages: allow for spacing, density, + order, emphasis, and wording variations. Also make sure that date, time, and + the like are internationalized and displayed according to the phone’s settings.

    Fast and responsive UI

    Touch feedback on all touchable items

    • Touch feedback adds a tactile feeling to the user interface. You should - ensure your app provides touch feedback on all touchable elements to reduce + ensure your app provides touch feedback on all touchable elements to reduce the perceived app latency as much as possible.
    • - Responsive interaction encourages deeper exploration of an app by - creating timely, logical, and delightful screen reactions to user input. - Responsive interaction elevates an app from an information-delivery service - to an experience that communicates using multiple visual and tactile + Responsive interaction encourages deeper exploration of an app by + creating timely, logical, and delightful screen reactions to user input. + Responsive interaction elevates an app from an information-delivery service + to an experience that communicates using multiple visual and tactile responses.
    • For more information, see the Android training on Customizing Touch + href="{@docRoot}training/material/animations.html#Touch">Customizing Touch Feedback.

    UI should always be interactive

    • Apps that are unresponsive when performing background activity feel slow - and reduce user satisfaction. Ensure your app always has a responsive UI - regardless of any background activity. Achieve this by performing network - operations or any heavy-duty operations in a background thread—keep the UI + and reduce user satisfaction. Ensure your app always has a responsive UI + regardless of any background activity. Achieve this by performing network + operations or any heavy-duty operations in a background thread—keep the UI thread as idle as you can.
    • Material Design apps use minimal visual changes when your app is loading - content by representing each operation with a single activity indicator. - Avoid blocking dialogs with loading indicators.
    • Empty - states occur when the regular content of a view can’t be shown. It might - be a list that has no items or a search that returns no results. Avoid - completely empty states. The most basic empty state displays a - non-interactive image and a text tagline. Where you don’t have an image, or - the image is still loading, you should always show either a static - placeholder, or create a dynamic placeholder by using the Palette + href="http://www.google.com/design/spec/patterns/empty-states.html">Empty + states occur when the regular content of a view can’t be shown. It might + be a list that has no items or a search that returns no results. Avoid + completely empty states. The most basic empty state displays a + non-interactive image and a text tagline. Where you don’t have an image, or + the image is still loading, you should always show either a static + placeholder, or create a dynamic placeholder by using the Palette library to generate placeholder colors that match the target image.
    • For more information, see the Android training on Keeping Your App + href="{@docRoot}training/articles/perf-anr.html">Keeping Your App Responsive.

    Target 60 frames per second on low-cost devices

    @@ -721,34 +721,34 @@ requests.

  • Ensure that your app always runs fast and smoothly, even on low-cost devices.
  • Overdraw can significantly slow down your app—it occurs when the pixels - are being drawn more than once per pass. An example of this is when you have - an image with a button placed on top of it. While some overdraw is - unavoidable, it should be minimized to ensure a smooth frame rate. Perform - Debug + are being drawn more than once per pass. An example of this is when you have + an image with a button placed on top of it. While some overdraw is + unavoidable, it should be minimized to ensure a smooth frame rate. Perform + Debug GPU overdraw on your app to ensure it is minimized.
  • Android devices refresh the screen at 60 frames per second (fps), meaning - your app has to update the screen within roughly 16 milliseconds. Profile - your app using on-device tools to see if and when your app is not + your app has to update the screen within roughly 16 milliseconds. Profile + your app using on-device tools to see if and when your app is not meeting this 16-ms average.
  • Reduce or remove animations on low-cost devices to lessen the burden on - the device’s CPU and GPU. For more information, see the Android training on - Improving Layout + the device’s CPU and GPU. For more information, see the Android training on + Improving Layout Performance.
  • -

    If anticipated start speed is low, use launch screen +

    If anticipated start speed is low, use launch screen on first load

    • The launch screen is a user’s first experience of your application. - Launching your app while displaying a blank canvas increases its perceived - loading time, so consider using a placeholder UI or a branded launch screen + Launching your app while displaying a blank canvas increases its perceived + loading time, so consider using a placeholder UI or a branded launch screen to reduce the perceived loading time.
    • A - placeholder UI is the most seamless launch transition, appropriate for + placeholder UI is the most seamless launch transition, appropriate for both app launches and in-app activity transitions.
    • - Branded launch screens provide momentary brand exposure, freeing the UI + Branded launch screens provide momentary brand exposure, freeing the UI to focus on content.
    • For more information on implementing splash screens, see the @@ -758,24 +758,24 @@ on first load
      • - Material Design is a visual language that synthesizes the classic - principles of good design with the innovation and possibility of technology - and science. Material Design aims to develop a single underlying system that - allows for a unified experience across platforms and device sizes. Consider - using key Material Design components so that users intuitively know how to + Material Design is a visual language that synthesizes the classic + principles of good design with the innovation and possibility of technology + and science. Material Design aims to develop a single underlying system that + allows for a unified experience across platforms and device sizes. Consider + using key Material Design components so that users intuitively know how to use your app.
      • Ready-to-use Material Design components are available via the Design Support - library. These components are supported in Android 2.1 (API level 7) and + href="{@docRoot}tools/support-library/features.html#design">Design Support + library. These components are supported in Android 2.1 (API level 7) and above.

      Localization

      • Your users could be from any part of the world and their first language - may not be yours. If you don’t present your app in a language that your - users can read, it is a missed opportunity. You should therefore + may not be yours. If you don’t present your app in a language that your + users can read, it is a missed opportunity. You should therefore localize your app for key regional languages.
      • -
      • To learn more, visit the Android training on To learn more, visit the Android training on Supporting Different Languages.
      diff --git a/docs/html/distribute/essentials/quality/core.jd b/docs/html/distribute/essentials/quality/core.jd index 0ff44eb97e00c..637eaac56ce4b 100644 --- a/docs/html/distribute/essentials/quality/core.jd +++ b/docs/html/distribute/essentials/quality/core.jd @@ -12,7 +12,7 @@ page.image=/distribute/images/core-quality-guidelines.jpg
    • Google Play
    • - +

      Testing

      1. Setting Up a Test Environment
      2. @@ -24,7 +24,7 @@ page.image=/distribute/images/core-quality-guidelines.jpg
      3. Tablet App Quality
      4. Optimize Your App
      - +
    @@ -85,7 +85,7 @@ page.image=/distribute/images/core-quality-guidelines.jpg ID - + Description diff --git a/docs/html/distribute/essentials/quality/tablets.jd b/docs/html/distribute/essentials/quality/tablets.jd index 2b2a5ae2d6ae0..3ff35f7518423 100644 --- a/docs/html/distribute/essentials/quality/tablets.jd +++ b/docs/html/distribute/essentials/quality/tablets.jd @@ -57,7 +57,7 @@ Xnonavpage=true

    The first step in delivering a great tablet app experience is making sure that it meets the core app quality criteria for all of the devices and form factors that the app is targeting. For complete information, see the Core App Quality Guidelines. +href="{@docRoot}distribute/essentials/quality/core.html">Core App Quality Guidelines.

    @@ -73,7 +73,7 @@ Before publishing, also ensure that your app passes the basic technical checks a

    If your app is already uploaded to the Google Play Developer Console, you - can see how it is doing against these checks + can see how it is doing against these checks by visiting the Optimization Tips page.

    @@ -505,7 +505,7 @@ attribute.
    <uses-feature android:name="android.hardware.telephony" android:required="false" />
    -
  • Similarly, check the manifest for <permission> elements that +
  • Similarly, check the manifest for <permission> elements that imply hardware feature requirements that not be appropriate for tablets. If you find such permissions, make sure to explicitly declare a corresponding diff --git a/docs/html/distribute/googleplay/cast.jd b/docs/html/distribute/googleplay/cast.jd index 937ab58901a6b..3112f8100c3e0 100644 --- a/docs/html/distribute/googleplay/cast.jd +++ b/docs/html/distribute/googleplay/cast.jd @@ -26,7 +26,7 @@ take full advantage of multiscreen experiences via Cast.

    Find out how to get your app Google - Cast-ready. + Cast-ready.

    Tips

    diff --git a/docs/html/distribute/googleplay/families/faq.jd b/docs/html/distribute/googleplay/families/faq.jd index 363dc91c114b3..663850f54df1b 100644 --- a/docs/html/distribute/googleplay/families/faq.jd +++ b/docs/html/distribute/googleplay/families/faq.jd @@ -10,7 +10,7 @@ page.metaDescription=Questions and answers about Designed for Families font-weight:bold; } - +

      In this document

      @@ -84,7 +84,7 @@ page.metaDescription=Questions and answers about Designed for Families
      No, you do not need to translate your privacy policy. However, if you distribute your apps in a few select countries, it is advised that you do - translate your privacy policy. + translate your privacy policy.
      @@ -173,7 +173,7 @@ page.metaDescription=Questions and answers about Designed for Families confirm that it is appropriate for families. Assuming your app complies with all program requirements, we expect that publishing time should not take any longer than normal; however, there may be a delay in publishing the app if it is - rejected during the Designed for Families review. + rejected during the Designed for Families review.
      @@ -301,7 +301,7 @@ page.metaDescription=Questions and answers about Designed for Families
      House ads are allowed, but they must comply with ads policies. + href="https://support.google.com/googleplay/android-developer/answer/6184502#ads">ads policies.
      diff --git a/docs/html/distribute/googleplay/families/start.jd b/docs/html/distribute/googleplay/families/start.jd index 0e773bd11c3aa..f174dae26da22 100644 --- a/docs/html/distribute/googleplay/families/start.jd +++ b/docs/html/distribute/googleplay/families/start.jd @@ -86,7 +86,7 @@ page.metaDescription=Join Designed for Families in just a few simple steps.

      Note: Published apps in the Designed for Families program - are also available to all users on Google Play. + are also available to all users on Google Play.

      diff --git a/docs/html/distribute/googleplay/tv.jd b/docs/html/distribute/googleplay/tv.jd index a35edbc45470d..981ba510dd76e 100644 --- a/docs/html/distribute/googleplay/tv.jd +++ b/docs/html/distribute/googleplay/tv.jd @@ -275,7 +275,7 @@ page.metaDescription=Distribute your apps, games, and content to Android TV. the criteria, you’ll receive a notification email sent to your developer account address, with a summary of the areas that you need to address. When you’ve made the necessary adjustments, you can upload a new version of your app to the Developer - Console. + Console.

      @@ -296,7 +296,7 @@ page.metaDescription=Distribute your apps, games, and content to Android TV.

    1. Approved — Your app was reviewed and approved. The app will be - made available directly to Android TV users. + made available directly to Android TV users.
    2. diff --git a/docs/html/distribute/tools/promote/device-art.jd b/docs/html/distribute/tools/promote/device-art.jd index 9b4dd1481aeb6..7fef02ff11e51 100644 --- a/docs/html/distribute/tools/promote/device-art.jd +++ b/docs/html/distribute/tools/promote/device-art.jd @@ -221,7 +221,7 @@ feature image or screenshots for your Google Play app listing.

      landOffset: [489,327], portRes: ['shadow', 'back', 'fore'], portOffset: [327,489], - portSize: [1440, 2560], + portSize: [1440, 2560], archived: true }, { diff --git a/docs/html/distribute/tools/promote/linking.jd b/docs/html/distribute/tools/promote/linking.jd index 025480b1f1bd1..13b15744d4053 100644 --- a/docs/html/distribute/tools/promote/linking.jd +++ b/docs/html/distribute/tools/promote/linking.jd @@ -18,7 +18,7 @@ page.metaDescription=Learn how to build links that take users to your published

      Google Play provides several link formats that let you bring users to your products in the way you want, from Android apps, web pages, ads, reviews, -articles, social media posts, and more.

      +articles, social media posts, and more.

      The link formats let you:

        diff --git a/docs/html/google/backup/signup.jd b/docs/html/google/backup/signup.jd index 598003dbe23b2..86518b6458f95 100644 --- a/docs/html/google/backup/signup.jd +++ b/docs/html/google/backup/signup.jd @@ -105,7 +105,7 @@ This is the terms of service for the Android Backup Service. 8.4 You agree that you shall not remove, obscure, or alter any proprietary rights notices (including copyright, trade mark notices) which may be affixed to or contained within the Service.

        9. License from Google

        -9.1 Subject to terms and conditions of these Terms, Google gives you a personal, worldwide, royalty-free, non-assignable and non-exclusive license to use the Service as provided to you by Google. This license is for the sole purpose of enabling you to use and enjoy the benefit of the Service as provided by Google, in the manner permitted by the Terms. +9.1 Subject to terms and conditions of these Terms, Google gives you a personal, worldwide, royalty-free, non-assignable and non-exclusive license to use the Service as provided to you by Google. This license is for the sole purpose of enabling you to use and enjoy the benefit of the Service as provided by Google, in the manner permitted by the Terms. 9.2 You may not (and you may not permit anyone else to) copy, modify, create a derivative work of, reverse engineer, decompile or otherwise attempt to extract the source code from the Service or any part thereof, unless this is expressly permitted or required by law, or unless you have been specifically told that you may do so by Google, in writing. @@ -208,7 +208,7 @@ with the Android Backup Service Terms of Service

        -

        Register with Android Backup Service

    @@ -234,7 +234,7 @@ onclick="onRegister(); return false;" >Register with Android Backup Service< ); } } - + function boxFocusChanged(obj, focused) { if (focused) { if(obj.value == DEFAULT_TEXT){ @@ -248,14 +248,14 @@ onclick="onRegister(); return false;" >Register with Android Backup Service< } } } - - + + function onFormInput() { /* verify that the TOS is agreed and a bit version is chosen */ var packagename = $("#pname").val(); if ($("input#agree").is(":checked") && packagename.length - && packagename != DEFAULT_TEXT) { + && packagename != DEFAULT_TEXT) { /* reveal the button */ $("a#registerButton").removeClass('disabled'); } else { diff --git a/docs/html/google/index.jd b/docs/html/google/index.jd index 027ba23a6e5b7..9b7ff0b8b48fe 100644 --- a/docs/html/google/index.jd +++ b/docs/html/google/index.jd @@ -53,7 +53,7 @@ footer.hide=1

    Google Play developer tools

    - Scale your publishing, manage your catalog, build revenue using Google Play developer tools. + Scale your publishing, manage your catalog, build revenue using Google Play developer tools.
    diff --git a/docs/html/google/play/licensing/adding-licensing.jd b/docs/html/google/play/licensing/adding-licensing.jd index 3bf4c1a613330..bfd4f91d83a1c 100644 --- a/docs/html/google/play/licensing/adding-licensing.jd +++ b/docs/html/google/play/licensing/adding-licensing.jd @@ -7,7 +7,7 @@ parent.link=index.html
    - +

    In this document

    1. Adding the Licensing Permission
    2. @@ -42,7 +42,7 @@ to close IPC connections
    3. Publishing a Licensed Application
    4. Where to Get Support
    - +
    @@ -572,7 +572,7 @@ the dontAllow() method on {@code LicenseCheckerCallback}.
  • In case of a recoverable local or server error, such as when the network is not available to send the request, {@code LicenseChecker} passes a {@code RETRY} response to -your {@code Policy} object's processServerResponse() method. +your {@code Policy} object's processServerResponse() method.

    Also, both the {@code allow()} and {@code dontAllow()} callback methods receive a reason argument. The {@code allow()} method's reason is usually {@code Policy.LICENSED} or {@code Policy.RETRY} and the {@code dontAllow()} reason is usually {@code @@ -672,7 +672,7 @@ private class MyLicenseCheckerCallback implements LicenseCheckerCallback { return; } displayResult(getString(R.string.dont_allow)); - + if (reason == Policy.RETRY) { // If the reason received from the policy is RETRY, it was probably // due to a loss of connection with the service, so we should give the @@ -854,9 +854,9 @@ sample application calls checkAccess() from a

    Embed your public key for licensing

    For each application, the Google Play service automatically -generates a 2048-bit RSA public/private key pair that is used for -licensing and in-app billing. The key pair is uniquely associated with the -application. Although associated with the application, the key pair is +generates a 2048-bit RSA public/private key pair that is used for +licensing and in-app billing. The key pair is uniquely associated with the +application. Although associated with the application, the key pair is not the same as the key that you use to sign your applications (or derived from it).

    The Google Play Developer Console exposes the public key for licensing to any @@ -876,11 +876,11 @@ your application's public key for licensing:

    href="http://play.google.com/apps/publish">Developer Console and sign in. Make sure that you sign in to the account from which the application you are licensing is published (or will be published).
  • -
  • In the application details page, locate the Services & APIs +
  • In the application details page, locate the Services & APIs link and click it.
  • -
  • In the Services & APIs page, locate the -Licensing & In-App Billing section. Your public key for -licensing is given in the +
  • In the Services & APIs page, locate the +Licensing & In-App Billing section. Your public key for +licensing is given in the Your License Key For This Application field.
  • diff --git a/docs/html/google/play/licensing/licensing-reference.jd b/docs/html/google/play/licensing/licensing-reference.jd index d4ca79a77cb8d..2b16299448c97 100644 --- a/docs/html/google/play/licensing/licensing-reference.jd +++ b/docs/html/google/play/licensing/licensing-reference.jd @@ -7,7 +7,7 @@ parent.link=index.html
    - +

    In this document

    1. LVL Classes and Interfaces
    2. @@ -418,7 +418,7 @@ responses in the allow() method. The count of {@code RETRY} respons maintained in the processServerResponse() method, not shown.

      -
          
      +
       public boolean allowAccess() {
           long ts = System.currentTimeMillis();
           if (mLastResponse == LicenseResponse.LICENSED) {
      diff --git a/docs/html/google/play/licensing/overview.jd b/docs/html/google/play/licensing/overview.jd
      index ecb384dc74ed3..8d7977e1cb009 100755
      --- a/docs/html/google/play/licensing/overview.jd
      +++ b/docs/html/google/play/licensing/overview.jd
      @@ -6,14 +6,14 @@ parent.link=index.html
       
       
      - +

      Quickview

      • Licensing allows you to verify your app was purchased from Google Play
      • Your app maintains control of how it enforces its licensing status
      • The service is free for all developers who publish on Google Play
      - +

      In this document

      1. License Responses are Secure
      2. @@ -21,7 +21,7 @@ parent.link=index.html
      3. Requirements and Limitations
      4. Replacement for Copy Protection
      - +
      @@ -107,10 +107,10 @@ response data using an RSA key pair that is shared exclusively between the Googl server and you.

      The licensing service generates a single licensing key pair for each -application and exposes the public key in your application's -Services & APIs page in the Developer Console. You must copy -the public key from the Developer Console and embed it in your application -source code. The server retains the private key internally and uses it to sign +application and exposes the public key in your application's +Services & APIs page in the Developer Console. You must copy +the public key from the Developer Console and embed it in your application +source code. The server retains the private key internally and uses it to sign license responses for the applications you publish with that account.

      When your application receives a signed response, it uses the embedded public @@ -209,7 +209,7 @@ practices in the following documents, you can help ensure that your implementati secure.

    3. Adding licensing to an application does not affect the way the application functions when run on a device that does not offer Google Play.
    4. -
    5. You can implement licensing controls for a free app, but only if you're using the service to +
    6. You can implement licensing controls for a free app, but only if you're using the service to provide APK expansion files.
    7. diff --git a/docs/html/google/play/publishing/multiple-apks.jd b/docs/html/google/play/publishing/multiple-apks.jd index fd4481dc076a3..a878fb3ab1ad6 100644 --- a/docs/html/google/play/publishing/multiple-apks.jd +++ b/docs/html/google/play/publishing/multiple-apks.jd @@ -250,11 +250,11 @@ If you can't avoid using both, be aware that for any conflicts in agreement betw
    8. Device feature sets -

      This is based on your manifest file's This is based on your manifest file's {@code } element(s).

      For example, you can provide one APK for devices that support multitouch and another -APK for devices that do not support multitouch. See +APK for devices that do not support multitouch. See Features Reference for a list of features supported by the platform.


      diff --git a/docs/html/guide/appendix/app-intents.jd b/docs/html/guide/appendix/app-intents.jd index 8898927f240f4..5fb004fff8563 100644 --- a/docs/html/guide/appendix/app-intents.jd +++ b/docs/html/guide/appendix/app-intents.jd @@ -89,13 +89,13 @@ excludeFromSuggestions=true pitchPanorama center-of-view in degrees from -90 (look straight up) to 90 (look straight down.) zoomPanorama zoom. 1.0 = normal zoom, 2.0 = zoomed in 2x, 3.0 = zoomed in 4x, and so on.
      - A zoom of 1.0 is 90 degree horizontal FOV for a nominal - landscape mode 4 x 3 aspect ratio display. - Android phones in portrait mode will adjust the zoom so that - the vertical FOV is approximately the same as the landscape vertical - FOV. This means that the horizontal FOV of an Android phone in portrait - mode is much narrower than in landscape mode. This is done to minimize - the fisheye lens effect that would be present if a 90 degree horizontal + A zoom of 1.0 is 90 degree horizontal FOV for a nominal + landscape mode 4 x 3 aspect ratio display. + Android phones in portrait mode will adjust the zoom so that + the vertical FOV is approximately the same as the landscape vertical + FOV. This means that the horizontal FOV of an Android phone in portrait + mode is much narrower than in landscape mode. This is done to minimize + the fisheye lens effect that would be present if a 90 degree horizontal FOV was used in portrait mode. mapZoomThe map zoom of the map location associated with this panorama. This value is passed on to the Maps activity when the Street View "Go to Maps" menu item is chosen. It corresponds to the z parameter in diff --git a/docs/html/guide/appendix/g-app-intents.jd b/docs/html/guide/appendix/g-app-intents.jd index 9ec72db2411fa..21c927b913b75 100644 --- a/docs/html/guide/appendix/g-app-intents.jd +++ b/docs/html/guide/appendix/g-app-intents.jd @@ -83,7 +83,7 @@ href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filter - Google Streetview + Google Streetview google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom VIEW diff --git a/docs/html/guide/appendix/glossary.jd b/docs/html/guide/appendix/glossary.jd index a200a6c0ff0e5..75a533ad9084e 100755 --- a/docs/html/guide/appendix/glossary.jd +++ b/docs/html/guide/appendix/glossary.jd @@ -15,7 +15,7 @@ excludeFromSuggestions=true
      .dex file
      -
      Compiled Android application code file. +
      Compiled Android application code file.

      Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in @@ -26,7 +26,7 @@ excludeFromSuggestions=true a string value assigned to an Intent. Action strings can be defined by Android or by a third-party developer. For example, android.intent.action.VIEW for a Web URL, or com.example.rumbler.SHAKE_PHONE for a custom application - to vibrate the phone. + to vibrate the phone.

      Related: Intent.

      @@ -41,8 +41,8 @@ excludeFromSuggestions=true
      adb
      Android Debug Bridge, a command-line debugging application included with the SDK. It provides tools to browse the device, copy tools on the device, and - forward ports for debugging. If you are developing in Android Studio, - adb is integrated into your development environment. See + forward ports for debugging. If you are developing in Android Studio, + adb is integrated into your development environment. See Android Debug Bridge for more information.
      @@ -90,7 +90,7 @@ excludeFromSuggestions=true
      DDMS
      Dalvik Debug Monitor Service, a GUI debugging application included with the SDK. It provides screen capture, log dump, and process - examination capabilities. If you are developing in Android Studio, + examination capabilities. If you are developing in Android Studio, DDMS is integrated into your development environment. See Using DDMS to learn more about the program.
      @@ -100,7 +100,7 @@ excludeFromSuggestions=true is not intended to persist in the history stack, contain complex layout, or perform complex actions. Android provides a default simple dialog for you with optional buttons, though you can define your own dialog layout. - The base class for dialogs is {@link android.app.Dialog Dialog}. + The base class for dialogs is {@link android.app.Dialog Dialog}.

      Related: Activity.

      Drawable
      @@ -113,7 +113,7 @@ excludeFromSuggestions=true — xml or bitmap files that describe the image. Drawable resources are compiled into subclasses of {@link android.graphics.drawable}. For more information about drawables and other resources, see Resources. + href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources.

      Related: Resources, Canvas

      @@ -133,7 +133,7 @@ excludeFromSuggestions=true based on the criteria supplied in the Intent and the Intent Filters defined by other applications. For more information, see Intents and - Intent Filters. + Intent Filters.

      Related: Intent Filter, Broadcast Receiver.

      @@ -147,7 +147,7 @@ excludeFromSuggestions=true application/activity that best matches the Intent and criteria. For more information, see Intents and - Intent Filters. + Intent Filters.

      Related: Intent, Broadcast Receiver.

      @@ -155,12 +155,12 @@ excludeFromSuggestions=true
      An application class that listens for Intents that are broadcast, rather than being sent to a single target application/activity. The system delivers a broadcast Intent to all interested broadcast receivers, which - handle the Intent sequentially. -

      Related: Intent, Intent + handle the Intent sequentially. +

      Related: Intent, Intent Filter.

      - +
      Layout Resource
      -
      An XML file that describes the layout of an Activity screen. +
      An XML file that describes the layout of an Activity screen.

      Related: Resources

      Manifest File
      @@ -175,15 +175,15 @@ excludeFromSuggestions=true
      A resizeable bitmap resource that can be used for backgrounds or other images on the device. See - Nine-Patch Stretchable Image for more information. + Nine-Patch Stretchable Image for more information.

      Related: Resources.

      OpenGL ES
      Android provides OpenGL ES libraries that you can use for fast, complex 3D images. It is harder to use than a Canvas object, but - better for 3D objects. The {@link android.opengl} and - {@link javax.microedition.khronos.opengles} packages expose - OpenGL ES functionality. + better for 3D objects. The {@link android.opengl} and + {@link javax.microedition.khronos.opengles} packages expose + OpenGL ES functionality.

      Related: Canvas, Surface

      Resources
      @@ -205,15 +205,15 @@ excludeFromSuggestions=true
      Service
      An object of class {@link android.app.Service} that runs in the background (without any UI presence) to perform various persistent - actions, such as playing music or monitoring network activity. + actions, such as playing music or monitoring network activity.

      Related: Activity

      Surface
      An object of type {@link android.view.Surface} representing a block of memory that gets composited to the screen. A Surface holds a Canvas object for drawing, and provides various helper methods to draw layers and resize - the surface. You should not use this class directly; use - {@link android.view.SurfaceView} instead. + the surface. You should not use this class directly; use + {@link android.view.SurfaceView} instead.

      Related: Canvas

      SurfaceView
      @@ -249,7 +249,7 @@ excludeFromSuggestions=true windows, and so on). It receives calls from its parent object (see viewgroup, below)to draw itself, and informs its parent object about where and how big it would like to be (which may or may not be respected by the - parent). For more information, see {@link android.view.View}. + parent). For more information, see {@link android.view.View}.

      Related: Viewgroup, Widget

      @@ -259,18 +259,18 @@ excludeFromSuggestions=true they can be, as well as for calling each to draw itself when appropriate. Some viewgroups are invisible and are for layout only, while others have an intrinsic UI (for instance, a scrolling list box). Viewgroups are all - in the {@link android.widget widget} package, but extend - {@link android.view.ViewGroup ViewGroup}. + in the {@link android.widget widget} package, but extend + {@link android.view.ViewGroup ViewGroup}.

      Related: View

      Widget
      One of a set of fully implemented View subclasses that render form elements and other UI components, such as a text box or popup menu. Because a widget is fully implemented, it handles measuring and drawing - itself and responding to screen events. Widgets are all in the + itself and responding to screen events. Widgets are all in the {@link android.widget} package.
      - for the user to interact with, typically bundled up in a single file (with an .apk suffix). Android ships with a rich set @@ -186,10 +186,10 @@ document), seamless, activity after activity, task after task.

      - +

      An activity handles a particular type of content (data) and accepts a - set of related user actions. Each activity has a + set of related user actions. Each activity has a lifecycle that is independent of the other activities in its application or task — each activity is @@ -283,7 +283,7 @@ independent of the other to the activity stack, so that pressing Back displays the previous activity on the stack. However, the user cannot use the Back button to go back further than the last visit to Home. The adding of an activity to - the current stack happens whether or not that activity begins a new + the current stack happens whether or not that activity begins a new task (as long as that task was started without going Home), so going back can let the user go back to activities in previous tasks. The user can get to tasks earlier than @@ -297,7 +297,7 @@ independent of the other designing the navigation, if you have screen A and you want the user to be able go to a subsequent screen B and then use the Back button to go back to screen A, then the screen A needs to be implemented as an - activity. The one exception to this rule is if your application + activity. The one exception to this rule is if your application takes control of the Back button and manages the navigation itself. @@ -340,7 +340,7 @@ itself. Send a text message with an attachment

    9. - View a YouTube video and share it by email with someone else + View a YouTube video and share it by email with someone else
    10. @@ -666,7 +666,7 @@ itself. mailto:info@example.com link, they are actually initiating an Intent object, or just an intent, which then gets resolved to a particular component (we consider only activity components here). - So, the result of a user touching a mailto: link is an Intent object + So, the result of a user touching a mailto: link is an Intent object that the system tries to match to an activity. If that Intent object was written explicitly naming an activity (an explicit intent), then the system immediately launches that activity in response to the user @@ -925,7 +925,7 @@ href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filter For instance, you could disable the user control that initiates the Intent object, or display a message to the user that lets them go to a location, such as Google Play, to download its application. - In this way, your code can start the activity (using either startActivity() + In this way, your code can start the activity (using either startActivity() or startActivityForResult()) only if the intent has tested to resolve to an activity that is actually present.

      @@ -947,7 +947,7 @@ href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filter launcher
      (typically implemented as a sliding drawer on the Home screen), or from a shortcut icon on the Home screen, or from the task switcher. (The mechanism for this is for the - activity to have an + activity to have an intent filter with action MAIN and category LAUNCHER.) @@ -1103,7 +1103,7 @@ MAIN and activity to be run.

      - +

      Notifications and App Widgets should provide consistent back behavior

      Notifications and app widgets are two common ways that a user can launch diff --git a/docs/html/guide/practices/ui_guidelines/icon_design.jd b/docs/html/guide/practices/ui_guidelines/icon_design.jd index 07266607ed4c2..6b546c9fd21df 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design.jd @@ -58,7 +58,7 @@ Screens

      -

      New Guides for App Designers!

      +

      New Guides for App Designers!

      Check out the new documents for designers at Android Design, including more guidelines for Iconography.

      @@ -72,13 +72,13 @@ professional to users.

      This document provides information to help you create icons for various parts of your application’s user interface that match the general styles used by the -Android 2.x framework. Following these guidelines will help you to create a +Android 2.x framework. Following these guidelines will help you to create a polished and unified experience for the user.

      The following documents discuss detailed guidelines for the common types of icons used throughout Android applications:

      -
      +
      Launcher Icons
      A Launcher icon is a graphic that represents your application on the device's Home screen and in the Launcher window.
      @@ -103,7 +103,7 @@ icons used throughout Android applications:

      graphically represent list items. An example is the Settings application.
      -

      To get started creating your icons more quickly, you can download +

      To get started creating your icons more quickly, you can download the Android Icon Templates Pack.

      @@ -142,7 +142,7 @@ section in the box at the top-right corner of this page.

      Android is designed to run on a variety of devices that offer a range of screen sizes and resolutions. When you design the icons for your application, it's important keep in mind that your application may be installed on any of -those devices. As described in the Supporting Multiple Screens document, the Android platform makes it straightforward for you to provide icons in such a way that they will be displayed properly on any device, @@ -158,7 +158,7 @@ your application, see Resource directory qualifiers for screen size and density.

      -

      For tips on how to create and manage icon sets for multiple densities, see +

      For tips on how to create and manage icon sets for multiple densities, see Tips for Designers.

      @@ -290,7 +290,7 @@ initially draw launcher icons on an 864x864 artboard, it will be easier and cleaner to tweak the icons when you scale the artboard down to the target sizes for final asset creation.

      - +

      When scaling, redraw bitmap layers as needed

      diff --git a/docs/html/guide/practices/ui_guidelines/icon_design_action_bar.jd b/docs/html/guide/practices/ui_guidelines/icon_design_action_bar.jd index 831de4569edd2..37657f4d1eccb 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design_action_bar.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design_action_bar.jd @@ -31,7 +31,7 @@ Screens
      -

      New Guides for App Designers!

      +

      New Guides for App Designers!

      Check out the new documents for designers at Android Design, including more guidelines for Iconography.

      diff --git a/docs/html/guide/practices/ui_guidelines/icon_design_dialog.jd b/docs/html/guide/practices/ui_guidelines/icon_design_dialog.jd index c958ed9a655ec..a7ee73f41a787 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design_dialog.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design_dialog.jd @@ -29,7 +29,7 @@ Screens
      -

      New Guides for App Designers!

      +

      New Guides for App Designers!

      Check out the new documents for designers at Android Design, including more guidelines for Iconography.

      diff --git a/docs/html/guide/practices/ui_guidelines/icon_design_launcher.jd b/docs/html/guide/practices/ui_guidelines/icon_design_launcher.jd index f47e186790a93..3bb1a627c85ce 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design_launcher.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design_launcher.jd @@ -28,7 +28,7 @@ Screens
      -

      New Guides for App Designers!

      +

      New Guides for App Designers!

      Check out the new documents for designers at Android Design, including more guidelines for Iconography.

      diff --git a/docs/html/guide/practices/ui_guidelines/icon_design_launcher_archive.jd b/docs/html/guide/practices/ui_guidelines/icon_design_launcher_archive.jd index 2df3a2250ef55..483e076ac52f4 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design_launcher_archive.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design_launcher_archive.jd @@ -95,7 +95,7 @@ but rather they are meant to emphasize the common approaches that your icons can share with others on the device. Figure 1, at right, provides examples.

      -

      Figure 1. Example launcher icons for Android 2.0 and diff --git a/docs/html/guide/practices/ui_guidelines/icon_design_list.jd b/docs/html/guide/practices/ui_guidelines/icon_design_list.jd index 29e1a9380de71..fa350bc2b6a7b 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design_list.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design_list.jd @@ -30,7 +30,7 @@ Screens

      -

      New Guides for App Designers!

      +

      New Guides for App Designers!

      Check out the new documents for designers at Android Design, including more guidelines for Iconography.

      diff --git a/docs/html/guide/practices/ui_guidelines/icon_design_menu.jd b/docs/html/guide/practices/ui_guidelines/icon_design_menu.jd index a5b35977fc0e1..25b23d0f628c3 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design_menu.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design_menu.jd @@ -34,7 +34,7 @@ Screens
      -

      New Guides for App Designers!

      +

      New Guides for App Designers!

      Check out the new documents for designers at Android Design, including more guidelines for Iconography.

      @@ -267,7 +267,7 @@ menu icon color palette. appropriate. For example, in Figure 3 the logical place for rounded corners is the roof and not the rest of the building. -
    11. All dimensions specified on this page are based on a 48x48 pixel artboard +
    12. All dimensions specified on this page are based on a 48x48 pixel artboard size with a 6 pixel safeframe.
    13. The menu icon effect (the outer glow) described in
    14. Final art must be exported as a transparent PNG file.
    15. -
    16. Templates for creating menu icons in Adobe Photoshop are available in the +
    17. Templates for creating menu icons in Adobe Photoshop are available in the Icon Templates Pack.
    18. diff --git a/docs/html/guide/practices/ui_guidelines/icon_design_status_bar.jd b/docs/html/guide/practices/ui_guidelines/icon_design_status_bar.jd index 4993adb0328b7..27df450e16732 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design_status_bar.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design_status_bar.jd @@ -42,7 +42,7 @@ Screens
      -

      New Guides for App Designers!

      +

      New Guides for App Designers!

      Check out the new documents for designers at Android Design, including more guidelines for Iconography.

      diff --git a/docs/html/guide/practices/ui_guidelines/icon_design_tab.jd b/docs/html/guide/practices/ui_guidelines/icon_design_tab.jd index cbe6706fb0677..308e6d092c1ed 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design_tab.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design_tab.jd @@ -34,7 +34,7 @@ Screens
      -

      New Guides for App Designers!

      +

      New Guides for App Designers!

      Check out the new documents for designers at Android Design, including more guidelines for Iconography.

      @@ -291,10 +291,10 @@ your application.

      the Android platform.

      Warning: -Because these resources can change between platform versions, you +Because these resources can change between platform versions, you should not reference the system's copy of the resources. If you want to use any icons or other internal drawable resources, you should store a -local copy of those icons or drawables in your application resources, +local copy of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system's copy changes. Note that the grid below is not intended to be complete.

      diff --git a/docs/html/guide/practices/ui_guidelines/index.jd b/docs/html/guide/practices/ui_guidelines/index.jd index 91a0725b82e3d..713109cf2bcf0 100644 --- a/docs/html/guide/practices/ui_guidelines/index.jd +++ b/docs/html/guide/practices/ui_guidelines/index.jd @@ -7,7 +7,7 @@ excludeFromSuggestions=true
      -

      New Guides for App Designers!

      +

      New Guides for App Designers!

      The Android UX team has put together a set of guidelines for the interaction and visual design of Android applications. The new collection provides an overview of Android styles, design patterns, building blocks for exceptional Android designs, and more.

      diff --git a/docs/html/guide/practices/ui_guidelines/menu_design.jd b/docs/html/guide/practices/ui_guidelines/menu_design.jd index bf87bdd124e7f..949752588a120 100644 --- a/docs/html/guide/practices/ui_guidelines/menu_design.jd +++ b/docs/html/guide/practices/ui_guidelines/menu_design.jd @@ -8,7 +8,7 @@ parent.link=index.html @@ -16,7 +16,7 @@ parent.link=index.html

      This document has been deprecated.

      -

      For design guidelines about adding user actions and other options, read the design guidelines +

      For design guidelines about adding user actions and other options, read the design guidelines for Action Bar or the developer guide about Menus.

      @@ -25,7 +25,7 @@ for Action Bar or the dev onclick="$('#naMessage').hide();$('#deprecatedSticker').show()" />
      - + @@ -37,7 +37,7 @@ onclick="$('#naMessage').hide();$('#deprecatedSticker').show()" />
      - +

      Quickview

        @@ -85,15 +85,15 @@ onclick="$('#naMessage').hide();$('#deprecatedSticker').show()" />
    -
    +

    A menu holds a set of commands (user actions) that are normally hidden, and are accessible by a button, key, or gesture. Menu commands provide a means - for performing operations and for navigating to other parts of your + for performing operations and for navigating to other parts of your application or other applications. Menus are useful for freeing screen space, as an alternative to placing functionality and navigation, in buttons or other - user controls in the content area of your application. + user controls in the content area of your application.

    @@ -102,7 +102,7 @@ onclick="$('#naMessage').hide();$('#deprecatedSticker').show()" /> the functionality and navigation for your application. Briefly:

    • The Options menu contains primary functionality that applies - globally to the current activity or starts a related activity. + globally to the current activity or starts a related activity. It is typically invoked by a user pressing a hard button, often labeled Menu.
    • The Context menu contains secondary functionality for the currently selected item. It is typically invoked by a user's touch & hold @@ -113,11 +113,11 @@ onclick="$('#naMessage').hide();$('#deprecatedSticker').show()" />

      All but the simplest applications have menus. The system automatically - lays the menus out and provides standard ways for users to access them. + lays the menus out and provides standard ways for users to access them. In this sense, they are familiar and dependable ways for users to access functionality across all applications. All menus are panels that "float" on top of the activity screen and are smaller than full screen, so that the - application is still visible around its edges. This is a visual reminder + application is still visible around its edges. This is a visual reminder that a menu is an intermediary operation that disappears once it's used.

      @@ -127,8 +127,8 @@ onclick="$('#naMessage').hide();$('#deprecatedSticker').show()" />

      Tour of the Menus

      -

      Note: Your menus and screens might not look -like those shown in this document; they may vary from one version of Android +

      Note: Your menus and screens might not look +like those shown in this document; they may vary from one version of Android or device to another.

      @@ -137,13 +137,13 @@ or device to another.

      The Options menu contains commands that apply globally across the current activity, or can start another activity. They do not apply to a selected - item in the content (a Context menu does that). + item in the content (a Context menu does that).

      - On most devices, a user presses the Menu button to access the Options menu, - as shown in the screenshot below. To close the menu, the user presses - Menu again, or presses the Back button. + On most devices, a user presses the Menu button to access the Options menu, + as shown in the screenshot below. To close the menu, the user presses + Menu again, or presses the Back button. In fact, to cancel out of any menu, press the Back button. (Pressing the Menu button or touching outside the menu also works.) Note that how to invoke this menu may be different on different devices. @@ -153,15 +153,15 @@ or device to another. Each activity activity has its own set of operations and therefore its own Options menu. - An application with multiple activities would have a different Options menu - for each activity. + An application with multiple activities would have a different Options menu + for each activity.

      For example, in the message list view of an email program, the Options menu - might let you search the messages, compose a new message, refresh the list, - or change the email settings. The compose view of an email program would - have a different Options menu, such as adding a CC field, attaching a file, + might let you search the messages, compose a new message, refresh the list, + or change the email settings. The compose view of an email program would + have a different Options menu, such as adding a CC field, attaching a file, or discarding the message.

      @@ -179,7 +179,7 @@ or device to another.
    • Options expanded menu - If the activity has more menu items than will fit on the icon menu, then the last icon is labeled "More" — selecting it - displays a list that can contain any number of menu items and will scroll + displays a list that can contain any number of menu items and will scroll as necessary.
    @@ -202,18 +202,18 @@ or device to another.

    A user can touch & hold on content on the screen to - access a Context menu (if one exists), as shown in the screenshot below. + access a Context menu (if one exists), as shown in the screenshot below. A Context menu is a list of menu items (commands) that can operate on the selected content. The command can either be part of the current - activity, or the system can pass the selected content along to - an operation in another activity (by way of an + activity, or the system can pass the selected content along to + an operation in another activity (by way of an intent).

    For example, in an email message list, a user can touch & hold on an email message to open a Context menu containing commands to read, - archive, or delete the message. + archive, or delete the message.

    @@ -231,7 +231,7 @@ or device to another. In the above example, if the user performs touch & hold on the contact "Obi Wan Kenobi", a Context menu opens. The commands provided in this Context menu are the complete set of actions that can be performed - on this contact. + on this contact.

    @@ -246,7 +246,7 @@ or device to another.

    Also note, as shown in the following screenshot, the Context menu and the next screen both hold the same complete set of commands that can be performed - on this contact. The Context menu displays the commands in a list, + on this contact. The Context menu displays the commands in a list, while the "View contact" activity splits them into various items in the Options menu, icon buttons and list items.

    @@ -268,10 +268,10 @@ or device to another.

    Text Commands in Context Menu

    - Text links and text fields in the content both have system-provided operations + Text links and text fields in the content both have system-provided operations that are common across all applications: operations such as "Select all", "Select text", - "Copy all", and "Add to dictionary". If the text field is editable, it also - has other operations, such as "Cut all" and "Input Method", and if text + "Copy all", and "Add to dictionary". If the text field is editable, it also + has other operations, such as "Cut all" and "Input Method", and if text is also on the clipboard, it has "Paste". The system automatically inserts the appropriate menu items into the Context menu of text links and text fields, as shown in the following screenshot. @@ -342,7 +342,7 @@ or device to another. An example of a selection-specific Context menu is when a user performs a touch & hold on a person's name in a list view of a contacts application. The Context menu would typically contain commands "View contact", "Call contact", - and "Edit contact". + and "Edit contact".

    Place the most frequently used operations first

    @@ -365,7 +365,7 @@ or device to another.

    Don't put commands only in a Context menu

    - If a user can fully access your application without using Context menus, + If a user can fully access your application without using Context menus, then it's designed properly! In general, if part of your application is inaccessible without using Context menus, then you need to duplicate those commands elsewhere.

    @@ -373,8 +373,8 @@ or device to another.

    Before opening a Context menu, it has no visual representation that identifies its presence (whereas the Options menu has the Menu button), and so is not - particularly discoverable. - Therefore, in general, a Context menu should duplicate commands + particularly discoverable. + Therefore, in general, a Context menu should duplicate commands found in the corresponding activity screen. For example, while it's useful to let the user call a phone number from a Context menu invoked by touch & hold on a name in a list of contacts, that operation should also @@ -388,7 +388,7 @@ or device to another. As described under shortcut, touching on an item in the content should activate the same command as touching the first item in the Context menu. Both cases should be the most intuitive - operation for that item. + operation for that item.

    Selecting an item in the content should perform the most intuitive operation

    @@ -427,13 +427,13 @@ or device to another.

    A Context menu should identify the selected item

    - When a user does touch & hold on an item, the Context menu should - contain the name of the selected item. Therefore, + When a user does touch & hold on an item, the Context menu should + contain the name of the selected item. Therefore, when creating a Context menu, be sure to include a title and the name of the - selected item so that it's clear to the user what the context is. + selected item so that it's clear to the user what the context is. For example, if a user selects a contact "Joan of Arc", put that name in the title of the Context menu (using - {@link android.view.ContextMenu#setHeaderTitle(java.lang.CharSequence) setHeaderTitle}). + {@link android.view.ContextMenu#setHeaderTitle(java.lang.CharSequence) setHeaderTitle}). Likewise, a command to edit the contact should be called "Edit contact", not just "Edit".

    @@ -442,7 +442,7 @@ or device to another.

    Put only the most important commands fixed on the screen

    - By putting commands in menus, you free up the screen to hold more content. + By putting commands in menus, you free up the screen to hold more content. On the other hand, fixing commands in the content area of an activity makes them more prominent and easy to use.

    @@ -456,7 +456,7 @@ or device to another. To give a command the highest prominence, ensuring the command is obvious and won't be overlooked.
    Example: A "Buy" button in a store application. -
  • +
  • When quick access to the command is important and going to the menu would be tedious or slow.
    Example: Next/Previous buttons or Zoom In/Out buttons in an image viewing application. @@ -494,7 +494,7 @@ or device to another. When a dialog is displayed, pressing the Menu button should do nothing. This also holds true for activities that look like dialogs. A dialog box is recognizable by being - smaller than full-screen, having zero to three buttons, is non-scrollable, and + smaller than full-screen, having zero to three buttons, is non-scrollable, and possibly a list of selectable items that can include checkboxes or radio buttons.

    @@ -520,12 +520,12 @@ true

    Sometimes a menu item's action cannot be performed — for example, - the "Forward" button in a browser cannot work until after the "Back" + the "Forward" button in a browser cannot work until after the "Back" button has been pressed. We recommend:

      -
    • +
    • In Options menu - disable the menu item, which dims the text and icon, turning it gray. This applies to menu items in both the icon menu and the "More" menu. It would be disorienting for the icon menu to change from 6 diff --git a/docs/html/guide/practices/ui_guidelines/widget_design.jd b/docs/html/guide/practices/ui_guidelines/widget_design.jd index cf2cd64d483a2..95c594dba972e 100644 --- a/docs/html/guide/practices/ui_guidelines/widget_design.jd +++ b/docs/html/guide/practices/ui_guidelines/widget_design.jd @@ -46,7 +46,7 @@ parent.link=index.html
      -

      New Guides for App Designers!

      +

      New Guides for App Designers!

      Check out the new documents for designers at Android Design.

      diff --git a/docs/html/guide/topics/admin/device-admin.jd b/docs/html/guide/topics/admin/device-admin.jd index e2fef04b75372..2a8583a83e7dc 100644 --- a/docs/html/guide/topics/admin/device-admin.jd +++ b/docs/html/guide/topics/admin/device-admin.jd @@ -135,60 +135,60 @@ can require PIN or passwords to have at least six characters. combination of letters and numbers. They may include symbolic characters. - + Complex password required Requires that passwords must contain at least a letter, a numerical digit, and a special symbol. Introduced in Android 3.0. - - + + Minimum letters required in password The minimum number of -letters required in the password for all admins or a particular one. Introduced in Android 3.0. +letters required in the password for all admins or a particular one. Introduced in Android 3.0. - - - - Minimum lowercase letters required in password - The minimum number of lowercase -letters required in the password for all admins or a particular one. Introduced in Android 3.0. + + + + Minimum lowercase letters required in password + The minimum number of lowercase +letters required in the password for all admins or a particular one. Introduced in Android 3.0. - - - Minimum non-letter characters required in password + + + Minimum non-letter characters required in password The minimum number of -non-letter characters required in the password for all admins or a particular one. Introduced in Android 3.0. - - - - Minimum numerical digits required in password - The minimum number of numerical digits required in the password for all admins or a particular one. Introduced in Android 3.0. +non-letter characters required in the password for all admins or a particular one. Introduced in Android 3.0. - - Minimum symbols required in password - The minimum number of symbols required in the password for all admins or a particular one. Introduced in Android 3.0. + + Minimum numerical digits required in password + The minimum number of numerical digits required in the password for all admins or a particular one. Introduced in Android 3.0. - - Minimum uppercase letters required in password - The minimum number of uppercase letters required in the password for all admins or a particular one. Introduced in Android 3.0. + + Minimum symbols required in password + The minimum number of symbols required in the password for all admins or a particular one. Introduced in Android 3.0. - - Password expiration timeout - When the password will expire, expressed as a delta in milliseconds from when a device admin sets the expiration timeout. Introduced in Android 3.0. + + Minimum uppercase letters required in password + The minimum number of uppercase letters required in the password for all admins or a particular one. Introduced in Android 3.0. - - Password history restriction + + Password expiration timeout + When the password will expire, expressed as a delta in milliseconds from when a device admin sets the expiration timeout. Introduced in Android 3.0. + + + + Password history restriction This policy prevents users from reusing the last n unique passwords. This policy is typically used in conjunction with {@link android.app.admin.DevicePolicyManager#setPasswordExpirationTimeout(android.content.ComponentName,long) setPasswordExpirationTimeout()}, which forces users to update their passwords after a specified amount of time has elapsed. -Introduced in Android 3.0. +Introduced in Android 3.0. - + Maximum failed password attempts Specifies how many times a user can enter the wrong password before the @@ -203,18 +203,18 @@ pressed a button before the device locks the screen. When this happens, users need to enter their PIN or passwords again before they can use their devices and access data. The value can be between 1 and 60 minutes. - -Require storage encryption -Specifies that the storage area should be encrypted, if the device supports it. + +Require storage encryption +Specifies that the storage area should be encrypted, if the device supports it. Introduced in Android 3.0. Disable camera - + Specifies that the camera should be disabled. Note that this doesn't have to be a permanent disabling. The camera can be enabled/disabled dynamically based on context, time, and so on. Introduced in Android 4.0. - + @@ -234,7 +234,7 @@ Administration API lets you do the following:

        The examples used in this document are based on the Device Administration API sample, which is included in the SDK samples (available through the -Android SDK Manager) and located on your system as +Android SDK Manager) and located on your system as <sdk_root>/ApiDemos/app/src/main/java/com/example/android/apis/app/DeviceAdminSample.java.

        The sample application offers a demo of device admin features. It presents users @@ -250,8 +250,8 @@ policies, the system returns an error.

      • Set how many failed password attempts can occur before the device is wiped (that is, restored to factory settings).
      • Set how long from now the password will expire.
      • -
      • Set the password history length (length refers to number of old passwords stored in the history). -This prevents users from reusing +
      • Set the password history length (length refers to number of old passwords stored in the history). +This prevents users from reusing one of the last n passwords they previously used.
      • Specify that the storage area should be encrypted, if the device supports it.
      • Set the maximum amount of inactive time that can elapse before the device @@ -259,7 +259,7 @@ locks.
      • Make the device lock immediately.
      • Wipe the device's data (that is, restore factory settings).
      • Disable the camera.
      • - +
      @@ -454,8 +454,8 @@ changes to prompt the user to activate the device admin application, as shown in

      Figure 2. Sample Application: Activating the Application

      -

      Below is the code that gets executed when the user clicks the Enable Admin checkbox. This has the effect of triggering the -{@link android.preference.Preference.OnPreferenceChangeListener#onPreferenceChange(android.preference.Preference, java.lang.Object) onPreferenceChange()} +

      Below is the code that gets executed when the user clicks the Enable Admin checkbox. This has the effect of triggering the +{@link android.preference.Preference.OnPreferenceChangeListener#onPreferenceChange(android.preference.Preference, java.lang.Object) onPreferenceChange()} callback. This callback is invoked when the value of this {@link android.preference.Preference} has been changed by the user and is about to be set and/or persisted. If the user is enabling the application, the display changes to prompt the user to activate the device admin application, as shown in figure 2. Otherwise, the device admin application is disabled.

      @@ -556,7 +556,7 @@ containing at least numeric characters.
      {@link android.app.admin.DevicePolicyManager#PASSWORD_QUALITY_COMPLEX}
      The user must have entered a password containing at least a letter, a numerical digit and -a special symbol.
      +a special symbol.
      {@link android.app.admin.DevicePolicyManager#PASSWORD_QUALITY_SOMETHING}
      The policy requires some kind @@ -581,7 +581,7 @@ example, you could set a policy that states that passwords must contain at least contents:

        -
      • {@link android.app.admin.DevicePolicyManager#setPasswordMinimumLetters(android.content.ComponentName,int) setPasswordMinimumLetters()}
      • +
      • {@link android.app.admin.DevicePolicyManager#setPasswordMinimumLetters(android.content.ComponentName,int) setPasswordMinimumLetters()}
      • {@link android.app.admin.DevicePolicyManager#setPasswordMinimumLowerCase(android.content.ComponentName,int) setPasswordMinimumLowerCase()}
      • @@ -622,8 +622,8 @@ int maxFailedPw; mDPM.setMaximumFailedPasswordsForWipe(mDeviceAdminSample, maxFailedPw);
        Set password expiration timeout
        -

        Beginning with Android 3.0, you can use the -{@link android.app.admin.DevicePolicyManager#setPasswordExpirationTimeout(android.content.ComponentName,long) setPasswordExpirationTimeout()} +

        Beginning with Android 3.0, you can use the +{@link android.app.admin.DevicePolicyManager#setPasswordExpirationTimeout(android.content.ComponentName,long) setPasswordExpirationTimeout()} method to set when a password will expire, expressed as a delta in milliseconds from when a device admin sets the expiration timeout. For example:

        DevicePolicyManager mDPM;
        @@ -632,18 +632,18 @@ long pwExpiration;
         ...
         mDPM.setPasswordExpirationTimeout(mDeviceAdminSample, pwExpiration);
         
        - +
        Restrict password based on history
        -

        Beginning with Android 3.0, you can use the -{@link android.app.admin.DevicePolicyManager#setPasswordHistoryLength(android.content.ComponentName,int) setPasswordHistoryLength()} +

        Beginning with Android 3.0, you can use the +{@link android.app.admin.DevicePolicyManager#setPasswordHistoryLength(android.content.ComponentName,int) setPasswordHistoryLength()} method to limit users' ability to reuse old passwords. This method takes a length parameter, which specifies how many old passwords are stored. When this policy is active, users cannot enter a new password that matches the last n passwords. This prevents users from using the same password over and over. This policy is typically used -in conjunction with +in conjunction with {@link android.app.admin.DevicePolicyManager#setPasswordExpirationTimeout(android.content.ComponentName,long) setPasswordExpirationTimeout()}, which forces users to update their passwords after a specified amount of time has elapsed.

        @@ -705,7 +705,7 @@ mDPM.setCameraDisabled(mDeviceAdminSample, mDisableCameraCheckbox.isChecked());<

        Storage encryption

        Beginning with Android 3.0, you can use the -{@link android.app.admin.DevicePolicyManager#setStorageEncryption(android.content.ComponentName,boolean) setStorageEncryption()} +{@link android.app.admin.DevicePolicyManager#setStorageEncryption(android.content.ComponentName,boolean) setStorageEncryption()} method to set a policy requiring encryption of the storage area, where supported.

        For example:

        diff --git a/docs/html/guide/topics/appwidgets/host.jd b/docs/html/guide/topics/appwidgets/host.jd index 169e388918e2a..7b00019239be1 100644 --- a/docs/html/guide/topics/appwidgets/host.jd +++ b/docs/html/guide/topics/appwidgets/host.jd @@ -4,7 +4,7 @@ page.tags=AppWidgetHost,home screen,launcher
        - +

        In this document

        1. Binding App Widgets @@ -32,58 +32,58 @@ to embed app widgets access to content. If you're building a Home replacement or a similar app, you can also allow the user to embed app widgets by implementing an {@link android.appwidget.AppWidgetHost}. -This is not something that most apps will ever need to do, but if you are -creating your own host, it's important to understand the contractual obligations +This is not something that most apps will ever need to do, but if you are +creating your own host, it's important to understand the contractual obligations a host implicitly agrees to.

          -

          This document focuses on the responsibilities involved in implementing a custom -{@link android.appwidget.AppWidgetHost}. For an example of how to implement an +

          This document focuses on the responsibilities involved in implementing a custom +{@link android.appwidget.AppWidgetHost}. For an example of how to implement an {@link android.appwidget.AppWidgetHost}, see the source code for the -Android Home screen +Android Home screen -Launcher. +Launcher. -

          Here is an overview of key classes and concepts involved in implementing a custom +

          Here is an overview of key classes and concepts involved in implementing a custom {@link android.appwidget.AppWidgetHost}:

            -
          • App Widget Host— - The {@link android.appwidget.AppWidgetHost} provides the interaction -with the AppWidget service for apps, like the home screen, that want to embed -app widgets in their UI. An {@link android.appwidget.AppWidgetHost} must have -an ID that is unique within the host's own package. This ID remains persistent +
          • App Widget Host— + The {@link android.appwidget.AppWidgetHost} provides the interaction +with the AppWidget service for apps, like the home screen, that want to embed +app widgets in their UI. An {@link android.appwidget.AppWidgetHost} must have +an ID that is unique within the host's own package. This ID remains persistent across all uses of the host. The ID is typically a hard-coded value that you assign in your application.
          • - +
          • App Widget ID— - Each app widget instance is assigned a unique ID at the time of binding -(see {@link android.appwidget.AppWidgetManager#bindAppWidgetIdIfAllowed bindAppWidgetIdIfAllowed()}, -discussed in more detail in Binding app widgets). -The unique ID is obtained by the host using {@link android.appwidget.AppWidgetHost#allocateAppWidgetId() allocateAppWidgetId()}. This ID is persistent across the lifetime of the widget, -that is, until it is deleted from the host. Any host-specific state (such as the -size and location of the widget) should be persisted by the hosting package and + Each app widget instance is assigned a unique ID at the time of binding +(see {@link android.appwidget.AppWidgetManager#bindAppWidgetIdIfAllowed bindAppWidgetIdIfAllowed()}, +discussed in more detail in Binding app widgets). +The unique ID is obtained by the host using {@link android.appwidget.AppWidgetHost#allocateAppWidgetId() allocateAppWidgetId()}. This ID is persistent across the lifetime of the widget, +that is, until it is deleted from the host. Any host-specific state (such as the +size and location of the widget) should be persisted by the hosting package and associated with the app widget ID.
          • - -
          • App Widget Host View— - {@link android.appwidget.AppWidgetHostView} can be thought of as a frame -that the widget is wrapped in whenever it needs to be displayed. An app widget -is assigned to an {@link android.appwidget.AppWidgetHostView} every time the + +
          • App Widget Host View— + {@link android.appwidget.AppWidgetHostView} can be thought of as a frame +that the widget is wrapped in whenever it needs to be displayed. An app widget +is assigned to an {@link android.appwidget.AppWidgetHostView} every time the widget is inflated by the host.
          • Options Bundle— -The {@link android.appwidget.AppWidgetHost} uses the options bundle to communicate -information to the {@link android.appwidget.AppWidgetProvider} about how the -widget is being displayed (for example, size range, and whether the widget is on -a lockscreen or the home screen). This information allows the -{@link android.appwidget.AppWidgetProvider} to tailor the widget's contents +The {@link android.appwidget.AppWidgetHost} uses the options bundle to communicate +information to the {@link android.appwidget.AppWidgetProvider} about how the +widget is being displayed (for example, size range, and whether the widget is on +a lockscreen or the home screen). This information allows the +{@link android.appwidget.AppWidgetProvider} to tailor the widget's contents and appearance based on how and where it is displayed. -You use +You use {@link android.appwidget.AppWidgetHostView#updateAppWidgetOptions(android.os.Bundle) updateAppWidgetOptions()} -and +and {@link android.appwidget.AppWidgetHostView#updateAppWidgetSize updateAppWidgetSize()} -to modify an app widget's -bundle. Both of these methods trigger a callback to the +to modify an app widget's +bundle. Both of these methods trigger a callback to the {@link android.appwidget.AppWidgetProvider}.

          @@ -98,15 +98,15 @@ app is running on.

          Binding app widgets on Android 4.0 and lower

          -

          On devices running Android version 4.0 and lower, users add app widgets -via a system activity that allows users to select a widget. This implicitly -does a permission check—that is, by adding the app widget, the user is -implicitly granting permission to your app to add app widgets to the host. -Here is an example that illustrates -this approach, taken from the original -Launcher. In this snippet, an event handler invokes -{@link android.app.Activity#startActivityForResult(android.content.Intent,int) startActivityForResult()} -with the request code {@code REQUEST_PICK_APPWIDGET} in response to a +

          On devices running Android version 4.0 and lower, users add app widgets +via a system activity that allows users to select a widget. This implicitly +does a permission check—that is, by adding the app widget, the user is +implicitly granting permission to your app to add app widgets to the host. +Here is an example that illustrates +this approach, taken from the original +Launcher. In this snippet, an event handler invokes +{@link android.app.Activity#startActivityForResult(android.content.Intent,int) startActivityForResult()} +with the request code {@code REQUEST_PICK_APPWIDGET} in response to a user action:

          @@ -118,9 +118,9 @@ public void onClick(DialogInterface dialog, int which) {
               ...
                   case AddAdapter.ITEM_APPWIDGET: {
                       ...
          -            int appWidgetId = 
          +            int appWidgetId =
                               Launcher.this.mAppWidgetHost.allocateAppWidgetId();
          -            Intent pickIntent = 
          +            Intent pickIntent =
                               new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
                       pickIntent.putExtra
                               (AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
          @@ -135,7 +135,7 @@ public void onClick(DialogInterface dialog, int which) {
           app widget to your activity. In the following example, the activity responds
           by calling {@code addAppWidget()} to add the app widget:

          -
          public final class Launcher extends Activity 
          +
          public final class Launcher extends Activity
                   implements View.OnClickListener, OnLongClickListener {
               ...
               @Override
          @@ -152,7 +152,7 @@ by calling {@code addAppWidget()} to add the app widget:

          completeAddAppWidget(data, mAddItemCellInfo, !mDesktopLocked); break; } - } + } ... } }
          @@ -164,7 +164,7 @@ needs to be configured before it's added:

          int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET); - AppWidgetProviderInfo appWidget = + AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId); if (appWidget.configure != null) { @@ -183,7 +183,7 @@ see Creating App Widget Configuration Activity.

          Once the app widget is ready, the next step is to do the -actual work of adding it to the workspace. The +actual work of adding it to the workspace. The original Launcher uses a method called {@code completeAddAppWidget()} to do this.

          @@ -201,12 +201,12 @@ binding. To use this improved process, your app must declare the

          But this is just the first step. At runtime the user must explicitly grant permission to your app to allow it to add app widgets to the host. To test whether your app has permission to add the widget, -you use the -{@link android.appwidget.AppWidgetManager#bindAppWidgetIdIfAllowed bindAppWidgetIdIfAllowed()} -method. +you use the +{@link android.appwidget.AppWidgetManager#bindAppWidgetIdIfAllowed bindAppWidgetIdIfAllowed()} +method. If {@link android.appwidget.AppWidgetManager#bindAppWidgetIdIfAllowed bindAppWidgetIdIfAllowed()} returns {@code false}, your app must display a dialog prompting the -user to grant permission +user to grant permission ("allow" or "always allow," to cover all future app widget additions). This snippet gives an example of how to display the dialog:

          @@ -218,9 +218,9 @@ intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options); startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
          -

          The host also has to check whether the user added +

          The host also has to check whether the user added an app widget that needs configuration. For more discussion of this topic, -see +see Creating an App Widget Configuration Activity.

          @@ -229,23 +229,23 @@ an App Widget Configuration Activity.

          @@ -273,7 +273,7 @@ from the Configuration Activity. This is a necessary step for many app widge they can be properly displayed.
        2. Every app widget specifies a minimum width and height in dps, as defined in the {@link android.appwidget.AppWidgetProviderInfo} metadata -(using {@link android.appwidget.AppWidgetProviderInfo#minWidth android:minWidth} and +(using {@link android.appwidget.AppWidgetProviderInfo#minWidth android:minWidth} and {@link android.appwidget.AppWidgetProviderInfo#minHeight android:minHeight}). Make sure that the widget is laid out with at least this many dps. For example, many hosts align icons and widgets in a grid. In this scenario, @@ -379,7 +379,7 @@ so it is not explicitly required to set this for a home screen host.

          for your app—for example, if your host is a home screen, ensure that the {@link android.appwidget.AppWidgetProviderInfo#widgetCategory android:widgetCategory} -attribute in the +attribute in the {@link android.appwidget.AppWidgetProviderInfo} metadata includes the flag {@link android.appwidget.AppWidgetProviderInfo#WIDGET_CATEGORY_HOME_SCREEN}. Similarly, for the lockscreen, ensure that field includes the flag {@link android.appwidget.AppWidgetProviderInfo#WIDGET_CATEGORY_KEYGUARD}. For more diff --git a/docs/html/guide/topics/appwidgets/index.jd b/docs/html/guide/topics/appwidgets/index.jd index c9575e025f053..7d555ed2d8d89 100644 --- a/docs/html/guide/topics/appwidgets/index.jd +++ b/docs/html/guide/topics/appwidgets/index.jd @@ -4,7 +4,7 @@ page.tags=home,AppWidgetProvider
          - +

          In this document

          1. The Basics
          2. @@ -21,7 +21,7 @@ Intents Activity
            1. Updating the App Widget -from +from the Configuration Activity
            @@ -33,7 +33,7 @@ from collections
          3. Keeping Collection Data Fresh
          4. -
          +
        @@ -50,10 +50,10 @@ collections

        App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and receive periodic updates. These views are -referred +referred to as Widgets in the user interface, and you can publish one with an App Widget provider. An application component -that is +that is able to hold other App Widgets is called an App Widget host. The screenshot below shows the Music App Widget.

        @@ -85,14 +85,14 @@ update frequency,
        Defines the basic methods that allow you to programmatically interface with the App Widget, based on broadcast events. Through it, you will receive broadcasts when the -App Widget is updated, +App Widget is updated, enabled, disabled and deleted.
        View layout
        Defines the initial layout for the App Widget, defined in XML.

        Additionally, you can implement an App Widget configuration Activity. This is -an optional +an optional {@link android.app.Activity} that launches when the user adds your App Widget and allows him or her to modify App Widget settings at create-time.

        @@ -117,7 +117,7 @@ application's

        The <receiver> element requires the -android:name +android:name attribute, which specifies the {@link android.appwidget.AppWidgetProvider} used by the App Widget.

        @@ -133,7 +133,7 @@ automatically sends all other App Widget broadcasts to the AppWidgetProvider as necessary.

        The <meta-data> element specifies the -{@link android.appwidget.AppWidgetProviderInfo} resource and requires the +{@link android.appwidget.AppWidgetProviderInfo} resource and requires the following attributes:

        • android:name - Specifies the metadata name. Use @@ -141,21 +141,21 @@ following attributes:

          to identify the data as the {@link android.appwidget.AppWidgetProviderInfo} descriptor.
        • android:resource - Specifies the {@link -android.appwidget.AppWidgetProviderInfo} +android.appwidget.AppWidgetProviderInfo} resource location.

        Adding the AppWidgetProviderInfo Metadata

        -

        The {@link android.appwidget.AppWidgetProviderInfo} defines the essential +

        The {@link android.appwidget.AppWidgetProviderInfo} defines the essential qualities of an App Widget, such as its minimum layout dimensions, its initial layout resource, how often to update the App Widget, and (optionally) a configuration Activity to launch at create-time. Define the AppWidgetProviderInfo object in an XML resource using a single <appwidget-provider> element and save it in the project's -res/xml/ +res/xml/ folder.

        For example:

        @@ -167,7 +167,7 @@ folder.

        android:updatePeriodMillis="86400000" android:previewImage="@drawable/preview" android:initialLayout="@layout/example_appwidget" - android:configure="com.example.android.ExampleAppWidgetConfigure" + android:configure="com.example.android.ExampleAppWidgetConfigure" android:resizeMode="horizontal|vertical" android:widgetCategory="home_screen"> </appwidget-provider> @@ -206,33 +206,33 @@ folder.

      • The updatePeriodMillis attribute defines how often the App Widget framework should request an update from the {@link -android.appwidget.AppWidgetProvider} by calling the -{@link android.appwidget.AppWidgetProvider#onUpdate(android.content.Context,android.appwidget.AppWidgetManager,int[]) onUpdate()} +android.appwidget.AppWidgetProvider} by calling the +{@link android.appwidget.AppWidgetProvider#onUpdate(android.content.Context,android.appwidget.AppWidgetManager,int[]) onUpdate()} callback method. The actual update is not guaranteed to occur exactly on time with this value and we suggest updating as infrequently as possible—perhaps no more than once an hour to conserve the battery. You might also allow the user to adjust the frequency in a configuration—some people might want a stock ticker to update every 15 -minutes, or maybe only four times a day. +minutes, or maybe only four times a day.

        Note: If the device is asleep when it -is time for an update +is time for an update (as defined by updatePeriodMillis), then the device will -wake up in order +wake up in order to perform the update. If you don't update more than once per hour, this -probably won't +probably won't cause significant problems for the battery life. If, however, you need -to update more +to update more frequently and/or you do not need to update while the device is asleep, -then you can instead +then you can instead perform updates based on an alarm that will not wake the device. To do -so, set an alarm with +so, set an alarm with an Intent that your AppWidgetProvider receives, using the {@link -android.app.AlarmManager}. +android.app.AlarmManager}. Set the alarm type to either {@link -android.app.AlarmManager#ELAPSED_REALTIME} or +android.app.AlarmManager#ELAPSED_REALTIME} or {@link android.app.AlarmManager#RTC}, which will only deliver the alarm when the device is awake. Then set -updatePeriodMillis to +updatePeriodMillis to zero ("0").

      • The initialLayout attribute points to the layout resource @@ -244,7 +244,7 @@ android.app.Activity} to launch when Widget properties. This is optional (read Creating an App Widget Configuration Activity below).
      • - +
      • The previewImage attribute specifies a preview of what the app widget will look like after it's configured, which the user sees when selecting the app widget. If not supplied, the user instead sees your @@ -255,7 +255,7 @@ using previewImage, see Setting a Preview Image. Introduced in Android 3.0.
      • The autoAdvanceViewId attribute specifies the view ID of the -app widget subview that should be auto-advanced by the widget's host. Introduced in Android 3.0.
      • +app widget subview that should be auto-advanced by the widget's host. Introduced in Android 3.0.
      • The resizeMode attribute specifies the rules by which a widget can be resized. You use this attribute to make homescreen widgets @@ -264,7 +264,7 @@ widget to show its resize handles, then drag the horizontal and/or vertical handles to change the size on the layout grid. Values for the resizeMode attribute include "horizontal", "vertical", and "none". To declare a widget as resizeable horizontally and vertically, supply the value -"horizontal|vertical". Introduced in Android 3.1.
      • +"horizontal|vertical". Introduced in Android 3.1.
      • The minResizeHeight attribute specifies the minimum height (in dps) to which the widget can be resized. This field has no effect if it is greater than {@code minHeight} or if @@ -296,7 +296,7 @@ View objects listed below, but before you begin designing your App Widget, please read and understand the App Widget -Design +Design Guidelines.

        Creating the App Widget layout is simple if you're @@ -306,7 +306,7 @@ However, you must be aware that App Widget layouts are based on {@link android.widget.RemoteViews}, which do not support every kind of layout or view widget.

        -

        A RemoteViews object (and, consequently, an App Widget) can support the +

        A RemoteViews object (and, consequently, an App Widget) can support the following layout classes:

          @@ -334,7 +334,7 @@ following layout classes:

          Descendants of these classes are not supported.

          -

          RemoteViews also supports {@link android.view.ViewStub}, which is an invisible, zero-sized View you can use +

          RemoteViews also supports {@link android.view.ViewStub}, which is an invisible, zero-sized View you can use to lazily inflate layout resources at runtime.

          @@ -386,7 +386,7 @@ to lazily inflate layout resources at runtime.

      - {@link android.appwidget.AppWidgetProvider#onAppWidgetOptionsChanged onAppWidgetOptionsChanged()} + {@link android.appwidget.AppWidgetProvider#onAppWidgetOptionsChanged onAppWidgetOptionsChanged()}
      This is called when the widget is first placed and any time the widget is resized. You can use this callback to show or hide content based on the widget's size ranges. You get the size ranges by calling {@link android.appwidget.AppWidgetManager#getAppWidgetOptions getAppWidgetOptions()}, which returns a {@link android.os.Bundle} that includes the following:

        -
      • {@link android.appwidget.AppWidgetManager#OPTION_APPWIDGET_MIN_WIDTH}—Contains +
      • {@link android.appwidget.AppWidgetManager#OPTION_APPWIDGET_MIN_WIDTH}—Contains the lower bound on the current width, in dp units, of a widget instance.
      • -
      • {@link android.appwidget.AppWidgetManager#OPTION_APPWIDGET_MIN_HEIGHT}—Contains +
      • {@link android.appwidget.AppWidgetManager#OPTION_APPWIDGET_MIN_HEIGHT}—Contains the lower bound on the current height, in dp units, of a widget instance.
      • {@link android.appwidget.AppWidgetManager#OPTION_APPWIDGET_MAX_WIDTH}—Contains the upper bound on the current width, in dp units, of a widget instance.
      • -
      • {@link android.appwidget.AppWidgetManager#OPTION_APPWIDGET_MAX_HEIGHT}—Contains +
      • {@link android.appwidget.AppWidgetManager#OPTION_APPWIDGET_MAX_HEIGHT}—Contains the upper bound on the current width, in dp units, of a widget instance.
      @@ -444,34 +444,34 @@ This callback was introduced in API Level 16 (Android 4.1). If you implement thi host.
      {@link android.appwidget.AppWidgetProvider#onEnabled(Context)}
      This is called when an instance the App Widget is created for the first -time. For example, if the user +time. For example, if the user adds two instances of your App Widget, this is only called the first time. If you need to open a new database or perform other setup that only needs to -occur once - for all App Widget instances, then this is a good place to do it.
      +occur once + for all App Widget instances, then this is a good place to do it.
      {@link android.appwidget.AppWidgetProvider#onDisabled(Context)}
      This is called when the last instance of your App Widget is deleted from -the App Widget host. - This is where you should clean up any work done in - {@link android.appwidget.AppWidgetProvider#onEnabled(Context)}, - such as delete a temporary database.
      +the App Widget host. + This is where you should clean up any work done in + {@link android.appwidget.AppWidgetProvider#onEnabled(Context)}, + such as delete a temporary database.
      {@link android.appwidget.AppWidgetProvider#onReceive(Context,Intent)}
      This is called for every broadcast and before each of the above callback methods. You normally don't need to implement this method because the default -AppWidgetProvider - implementation filters all App Widget broadcasts and calls the above - methods as appropriate.
      +AppWidgetProvider + implementation filters all App Widget broadcasts and calls the above + methods as appropriate. -

      The most important AppWidgetProvider callback is -{@link android.appwidget.AppWidgetProvider#onUpdate(android.content.Context, android.appwidget.AppWidgetManager, int[]) onUpdate()} +

      The most important AppWidgetProvider callback is +{@link android.appwidget.AppWidgetProvider#onUpdate(android.content.Context, android.appwidget.AppWidgetManager, int[]) onUpdate()} because it is called when each App Widget is added to a host (unless you use a configuration Activity). If your App Widget accepts any user interaction events, then you need to register the event handlers in this callback. If your App Widget doesn't create temporary -files or databases, or perform other work that requires clean-up, then -{@link android.appwidget.AppWidgetProvider#onUpdate(android.content.Context, android.appwidget.AppWidgetManager, int[]) onUpdate()} +files or databases, or perform other work that requires clean-up, then +{@link android.appwidget.AppWidgetProvider#onUpdate(android.content.Context, android.appwidget.AppWidgetManager, int[]) onUpdate()} may be the only callback method you need to define. For example, if you want an App Widget with a button that launches an Activity when clicked, you could use the following @@ -503,9 +503,9 @@ public class ExampleAppWidgetProvider extends AppWidgetProvider { } -

      This AppWidgetProvider defines only the +

      This AppWidgetProvider defines only the {@link -android.appwidget.AppWidgetProvider#onUpdate(android.content.Context, android.appwidget.AppWidgetManager, int[]) onUpdate()} +android.appwidget.AppWidgetProvider#onUpdate(android.content.Context, android.appwidget.AppWidgetManager, int[]) onUpdate()} method for the purpose of defining a {@link android.app.PendingIntent} that launches an {@link android.app.Activity} and attaching it to the App Widget's button with {@link @@ -528,8 +528,8 @@ running after the callback methods return (see {@link android.content.BroadcastReceiver} for information about the broadcast lifecycle). If your App Widget setup process can take several seconds (perhaps while performing web requests) and you require that your process continues, -consider starting a {@link android.app.Service} in the -{@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) onUpdate()} +consider starting a {@link android.app.Service} in the +{@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) onUpdate()} method. From within the Service, you can perform your own updates to the App Widget without worrying about the AppWidgetProvider closing down due to an Application @@ -537,7 +537,7 @@ Not Responding (ANR) error. See the Wiktionary sample's AppWidgetProvider for an example of an App Widget running a {@link android.app.Service}.

      -

      Also see the Also see the ExampleAppWidgetProvider.java sample class.

      @@ -546,9 +546,9 @@ sample class.

      {@link android.appwidget.AppWidgetProvider} is just a convenience class. If you would like -to receive the App Widget broadcasts directly, you can implement your own -{@link android.content.BroadcastReceiver} or override the -{@link android.appwidget.AppWidgetProvider#onReceive(Context,Intent)} callback. +to receive the App Widget broadcasts directly, you can implement your own +{@link android.content.BroadcastReceiver} or override the +{@link android.appwidget.AppWidgetProvider#onReceive(Context,Intent)} callback. The Intents you need to care about are as follows:

      • {@link android.appwidget.AppWidgetManager#ACTION_APPWIDGET_UPDATE}
      • @@ -565,11 +565,11 @@ The Intents you need to care about are as follows:

        If you would like the user to configure settings when he or she adds a new App Widget, you can create an App Widget configuration Activity. This {@link -android.app.Activity} +android.app.Activity} will be automatically launched by the App Widget host and allows the user to configure available settings for the App Widget at create-time, such as the App Widget -color, size, +color, size, update period or other functionality settings.

        The configuration Activity should be declared as a normal Activity in the @@ -588,8 +588,8 @@ so the Activity needs to accept this Intent. For example:

        Also, the Activity must be declared in the AppWidgetProviderInfo XML file, -with the -android:configure attribute (see Adding +with the +android:configure attribute (see Adding the AppWidgetProviderInfo Metadata above). For example, the configuration Activity can be declared like this:

        @@ -597,13 +597,13 @@ can be declared like this:

         <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
             ...
        -    android:configure="com.example.android.ExampleAppWidgetConfigure" 
        +    android:configure="com.example.android.ExampleAppWidgetConfigure"
             ... >
         </appwidget-provider>
         

        Notice that the Activity is declared with a fully-qualified namespace, -because +because it will be referenced from outside your package scope.

        That's all you need to get started with a configuration Activity. Now all you @@ -612,21 +612,21 @@ Activity. There are, however, two important things to remember when you implement the Activity:

        • The App Widget host calls the configuration Activity and the configuration -Activity should always +Activity should always return a result. The result should include the App Widget ID passed by the Intent that launched the Activity (saved in the Intent extras as {@link android.appwidget.AppWidgetManager#EXTRA_APPWIDGET_ID}).
        • -
        • The - {@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) onUpdate()} +
        • The + {@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) onUpdate()} method will not be called when the App Widget is created (the system will not send the ACTION_APPWIDGET_UPDATE broadcast when a configuration Activity is launched). It is the responsibility of the configuration Activity to -request an update from the - AppWidgetManager when the App Widget is first created. However, -{@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) onUpdate()} +request an update from the + AppWidgetManager when the App Widget is first created. However, +{@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) onUpdate()} will be called for subsequent updates—it is only skipped the first time.
        @@ -641,8 +641,8 @@ configuration Activity

        When an App Widget uses a configuration Activity, it is the responsibility of the Activity -to update the App Widget when configuration is complete. -You can do so by requesting an update directly from the +to update the App Widget when configuration is complete. +You can do so by requesting an update directly from the {@link android.appwidget.AppWidgetManager}.

        Here's a summary of the procedure to properly update the App Widget and close @@ -655,7 +655,7 @@ Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { mAppWidgetId = extras.getInt( - AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } @@ -696,7 +696,7 @@ reaching the end, the App Widget host is notified that the configuration was cancelled and the App Widget will not be added.

        -

        See the See the ExampleAppWidgetConfigure.java sample class in ApiDemos for an example.

        @@ -708,7 +708,7 @@ sample class in ApiDemos for an example.

        android.appwidget.AppWidgetProviderInfo#previewImage} field, which specifies a preview of what the app widget looks like. This preview is shown to the user from the widget picker. If this field is not supplied, the app widget's icon is used for -the preview.

        +the preview.

        This is how you specify this setting in XML:

        @@ -742,12 +742,12 @@ list. For an example, see the Gmail app widget.
        {@link android.widget.GridView}
        A view that shows items in two-dimensional scrolling grid. For an example, see the Bookmarks app -widget.
        +widget.
        {@link android.widget.StackView}
        A stacked card view (kind of like a rolodex), where the user can flick the front card up/down to see the previous/next card, respectively. Examples include -the YouTube and Books app widgets. 
        +the YouTube and Books app widgets. 
        {@link android.widget.AdapterViewFlipper}
        An adapter-backed simple {@link @@ -764,7 +764,7 @@ must include extra architecture to support their use in app widgets. In the context of an app widget, the {@link android.widget.Adapter} is replaced by a {@link android.widget.RemoteViewsService.RemoteViewsFactory RemoteViewsFactory}, which is simply a thin wrapper around the {@link android.widget.Adapter} -interface. +interface. When requested for a specific item in the collection, the {@link android.widget.RemoteViewsService.RemoteViewsFactory RemoteViewsFactory} creates @@ -782,7 +782,7 @@ interface for an adapter between a collection view (such as {@link android.widget.ListView}, {@link android.widget.GridView}, and so on) and the underlying data for that view. From the StackView Widget -sample, here is an example of the boilerplate code you use to implement +sample, here is an example of the boilerplate code you use to implement this service and interface:

        @@ -813,13 +813,13 @@ sample:

        This sample consists of a stack of 10 views, which display the values "0!" through "9!" The sample -app widget has these primary behaviors:

        +app widget has these primary behaviors:

        • The user can vertically fling the top view in the app widget to display the next or previous view. This is a built-in StackView -behavior.
        • +behavior.
        • Without any user interaction, the app widget automatically advances through @@ -828,17 +828,17 @@ its views in sequence, like a slide show. This is due to the setting res/xml/stackwidgetinfo.xml file. This setting applies to the view ID, which in this case is the view ID of the stack view.
        • - +
        • If the user touches the top view, the app widget displays the {@link android.widget.Toast} message "Touched view n," where n is the index (position) of the touched view. For more discussion of -how this is implemented, see +how this is implemented, see Adding behavior to individual items.

        Implementing app widgets with collections

        -

        To implement an app widget with collections, you follow the same basic steps +

        To implement an app widget with collections, you follow the same basic steps you would use to implement any app widget. The following sections describe the additional steps you need to perform to implement an app widget with collections.

        @@ -940,7 +940,7 @@ collection:

        int[] appWidgetIds) { // update each of the app widgets with the remote adapter for (int i = 0; i < appWidgetIds.length; ++i) { - + // Set up the intent that starts the StackViewService, which will // provide the views for this collection. Intent intent = new Intent(context, StackWidgetService.class); @@ -949,13 +949,13 @@ int[] appWidgetIds) { intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); // Instantiate the RemoteViews object for the app widget layout. RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout); - // Set up the RemoteViews object to use a RemoteViews adapter. + // Set up the RemoteViews object to use a RemoteViews adapter. // This adapter connects // to a RemoteViewsService through the specified intent. // This is how you populate the data. rv.setRemoteAdapter(appWidgetIds[i], R.id.stack_view, intent); - - // The empty view is displayed when the collection has no items. + + // The empty view is displayed when the collection has no items. // It should be in the same layout used to instantiate the RemoteViews // object above. rv.setEmptyView(R.id.stack_view, R.id.empty_view); @@ -963,12 +963,12 @@ int[] appWidgetIds) { // // Do additional processing specific to this app widget... // - - appWidgetManager.updateAppWidget(appWidgetIds[i], rv); + + appWidgetManager.updateAppWidget(appWidgetIds[i], rv); } super.onUpdate(context, appWidgetManager, appWidgetIds); } - +

        RemoteViewsService class

        As described above, your {@link android.widget.RemoteViewsService} subclass provides the {@link android.widget.RemoteViewsService.RemoteViewsFactory -RemoteViewsFactory} used to populate the remote collection view.

        +RemoteViewsFactory} used to populate the remote collection view.

        Specifically, you need to perform these steps:

        @@ -993,7 +993,7 @@ perform these steps:

      • Subclass {@link android.widget.RemoteViewsService}. {@link android.widget.RemoteViewsService} is the service through which a remote adapter can request {@link android.widget.RemoteViews}.
      • - +
      • In your {@link android.widget.RemoteViewsService} subclass, include a class that implements the {@link android.widget.RemoteViewsService.RemoteViewsFactory RemoteViewsFactory} @@ -1027,12 +1027,12 @@ functions as an adapter to glue the data to the remote collection view.

        The two most important methods you need to implement for your {@link android.widget.RemoteViewsService.RemoteViewsFactory RemoteViewsFactory} -subclass are +subclass are {@link android.widget.RemoteViewsService.RemoteViewsFactory#onCreate() onCreate()} and {@link android.widget.RemoteViewsService.RemoteViewsFactory#getViewAt(int) getViewAt()} -.

        +.

        The system calls {@link android.widget.RemoteViewsService.RemoteViewsFactory#onCreate() onCreate()} when @@ -1047,7 +1047,7 @@ array and the text they contain is displayed

        Here is an excerpt from the StackView Widget -sample's +sample's {@link android.widget.RemoteViewsService.RemoteViewsFactory RemoteViewsFactory} implementation that shows portions of the {@link android.widget.RemoteViewsService.RemoteViewsFactory#onCreate() onCreate()} @@ -1081,7 +1081,7 @@ RemoteViewsService.RemoteViewsFactory { RemoteViewsFactory} method {@link android.widget.RemoteViewsService.RemoteViewsFactory#getViewAt(int) getViewAt()} returns a {@link android.widget.RemoteViews} object corresponding to the data at -the specified position in the data set. Here is an excerpt from +the specified position in the data set. Here is an excerpt from the StackView Widget sample's {@link @@ -1089,8 +1089,8 @@ android.widget.RemoteViewsService.RemoteViewsFactory RemoteViewsFactory} implementation:

        public RemoteViews getViewAt(int position) {
        -   
        -    // Construct a remote views item based on the app widget item XML file, 
        +
        +    // Construct a remote views item based on the app widget item XML file,
             // and set the text based on the position.
             RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_item);
             rv.setTextViewText(R.id.widget_item, mWidgetItems.get(position).text);
        @@ -1104,7 +1104,7 @@ implementation:

        The above sections show you how to bind your data to your app widget collection. But what if you want to add dynamic behavior to the individual items -in your collection view?

        +in your collection view?

        As described in Using the AppWidgetProvider Class, you normally use {@link @@ -1122,7 +1122,7 @@ android.widget.RemoteViews#setOnClickFillInIntent(int, android.content.Intent) setOnClickFillInIntent()}. This entails setting up up a pending intent template for your collection view, and then setting a fill-in intent on each item in the collection via your {@link android.widget.RemoteViewsService.RemoteViewsFactory -RemoteViewsFactory}.

        +RemoteViewsFactory}.

        This section uses the StackView Widget sample to describe how to add behavior to individual items. In the TOAST_ACTION.

      • When the user touches a view, the intent is fired and it broadcasts TOAST_ACTION.
      • - +
      • This broadcast is intercepted by the StackWidgetProvider's {@link android.appwidget.AppWidgetProvider#onReceive(android.content.Context, android.content.Intent) onReceive()} method, and the app widget displays the @@ -1154,7 +1154,7 @@ href="{@docRoot}resources/samples/StackWidget/index.html">StackView Widget sample uses a broadcast, but typically an app widget would simply launch an activity in a scenario like this one.

        -
        Setting up the pending intent template
        +
        Setting up the pending intent template

        The StackWidgetProvider ({@link android.appwidget.AppWidgetProvider} subclass) sets up a pending intent. @@ -1162,7 +1162,7 @@ Individuals items of a collection cannot set up their own pending intents. Instead, the collection as a whole sets up a pending intent template, and the individual items set a fill-in intent to create unique behavior on an item-by-item -basis.

        +basis.

        This class also receives the broadcast that is sent when the user touches a view. It processes this event in its {@link @@ -1179,7 +1179,7 @@ message for the current view.

            ... // Called when the BroadcastReceiver receives an Intent broadcast. - // Checks to see whether the intent's action is TOAST_ACTION. If it is, the app widget + // Checks to see whether the intent's action is TOAST_ACTION. If it is, the app widget // displays a Toast message for the current item. @Override public void onReceive(Context context, Intent intent) { @@ -1192,12 +1192,12 @@ message for the current view.

            }     super.onReceive(context, intent); } - + @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // update each of the app widgets with the remote adapter     for (int i = 0; i < appWidgetIds.length; ++i) { - +     // Sets up the intent that points to the StackViewService that will     // provide the views for this collection.     Intent intent = new Intent(context, StackWidgetService.class); @@ -1207,7 +1207,7 @@ message for the current view.

            intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));     RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout);     rv.setRemoteAdapter(appWidgetIds[i], R.id.stack_view, intent); - +     // The empty view is displayed when the collection has no items. It should be a sibling     // of the collection view.     rv.setEmptyView(R.id.stack_view, R.id.empty_view); @@ -1227,13 +1227,13 @@ message for the current view.

            PendingIntent toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent,     PendingIntent.FLAG_UPDATE_CURRENT);     rv.setPendingIntentTemplate(R.id.stack_view, toastPendingIntent); - +     appWidgetManager.updateAppWidget(appWidgetIds[i], rv); } super.onUpdate(context, appWidgetManager, appWidgetIds); } } - +
        Setting the fill-in Intent

        Your {@link android.widget.RemoteViewsService.RemoteViewsFactory @@ -1274,17 +1274,17 @@ class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {        ...     }     ... - - // Given the position (index) of a WidgetItem in the array, use the item's text value in + + // Given the position (index) of a WidgetItem in the array, use the item's text value in // combination with the app widget item XML file to construct a RemoteViews object.     public RemoteViews getViewAt(int position) {         // position will always range from 0 to getCount() - 1. - +         // Construct a RemoteViews item based on the app widget item XML file, and set the         // text based on the position.         RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_item);         rv.setTextViewText(R.id.widget_item, mWidgetItems.get(position).text); - +         // Next, set a fill-intent, which will be used to fill in the pending intent template         // that is set on the collection view in StackWidgetProvider.         Bundle extras = new Bundle(); @@ -1294,9 +1294,9 @@ class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { // Make it possible to distinguish the individual on-click // action of a given item     rv.setOnClickFillInIntent(R.id.widget_item, fillInIntent); - +     ... - +     // Return the RemoteViews object.     return rv; } diff --git a/docs/html/guide/topics/connectivity/bluetooth-le.jd b/docs/html/guide/topics/connectivity/bluetooth-le.jd index 3d606863052a2..ba742eeef8a2a 100644 --- a/docs/html/guide/topics/connectivity/bluetooth-le.jd +++ b/docs/html/guide/topics/connectivity/bluetooth-le.jd @@ -171,7 +171,7 @@ include the following in your app's manifest:

        However, if you want to make your app available to devices that don't support BLE, -you should still include this element in your app's manifest, but set {@code required="false"}. +you should still include this element in your app's manifest, but set {@code required="false"}. Then at run-time you can determine BLE availability by using {@link android.content.pm.PackageManager#hasSystemFeature PackageManager.hasSystemFeature()}: diff --git a/docs/html/guide/topics/connectivity/bluetooth.jd b/docs/html/guide/topics/connectivity/bluetooth.jd index 96008c5c5701a..07fcd09a751ce 100644 --- a/docs/html/guide/topics/connectivity/bluetooth.jd +++ b/docs/html/guide/topics/connectivity/bluetooth.jd @@ -4,55 +4,55 @@ page.tags=wireless,bluetoothadapter,bluetoothdevice

        - +

        In this document

        -
          +
          1. The Basics
          2. Bluetooth Permissions
          3. -
          4. Setting Up Bluetooth
          5. -
          6. Finding Devices -
              -
            1. Querying paired devices
            2. -
            3. Discovering devices
            4. -
          7. -
          8. Connecting Devices -
              -
            1. Connecting as a server
            2. -
            3. Connecting as a client
            4. -
          9. +
          10. Setting Up Bluetooth
          11. +
          12. Finding Devices +
              +
            1. Querying paired devices
            2. +
            3. Discovering devices
            4. +
          13. +
          14. Connecting Devices +
              +
            1. Connecting as a server
            2. +
            3. Connecting as a client
            4. +
          15. Managing a Connection
          16. -
          17. Working with Profiles +
          18. Working with Profiles
            1. Vendor-specific AT commands
            2. Health Device Profile
          19. -
          - -

          Key classes

          -
            -
          1. {@link android.bluetooth.BluetoothAdapter}
          2. -
          3. {@link android.bluetooth.BluetoothDevice}
          4. -
          5. {@link android.bluetooth.BluetoothSocket}
          6. -
          7. {@link android.bluetooth.BluetoothServerSocket}
          8. -
          - -

          Related samples

          -
            -
          1. Bluetooth Chat
          2. +
          + +

          Key classes

          +
            +
          1. {@link android.bluetooth.BluetoothAdapter}
          2. +
          3. {@link android.bluetooth.BluetoothDevice}
          4. +
          5. {@link android.bluetooth.BluetoothSocket}
          6. +
          7. {@link android.bluetooth.BluetoothServerSocket}
          8. +
          + +

          Related samples

          +
            +
          1. Bluetooth Chat
          2. Bluetooth HDP (Health Device Profile)
          3. -
          - -
        -
        - - + + + + + +

        The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs. These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint -wireless features.

        - +wireless features.

        +

        Using the Bluetooth APIs, an Android application can perform the following:

      • + +
        {@link android.bluetooth.BluetoothDevice}
        Represents a remote Bluetooth device. Use this to request a connection with a remote device through a {@link android.bluetooth.BluetoothSocket} or query information about the -device such as its name, address, class, and bonding state.
        - -
        {@link android.bluetooth.BluetoothSocket}
        +device such as its name, address, class, and bonding state. + +
        {@link android.bluetooth.BluetoothSocket}
        Represents the interface for a Bluetooth socket (similar to a TCP {@link java.net.Socket}). This is the connection point that allows an application to exchange data with another Bluetooth device via InputStream -and OutputStream.
        - -
        {@link android.bluetooth.BluetoothServerSocket}
        +and OutputStream. + +
        {@link android.bluetooth.BluetoothServerSocket}
        Represents an open server socket that listens for incoming requests (similar to a TCP {@link java.net.ServerSocket}). In order to connect two Android devices, one device must open a server socket with this class. When a remote Bluetooth device makes a connection request to the this device, the {@link android.bluetooth.BluetoothServerSocket} will return a connected {@link android.bluetooth.BluetoothSocket} when the -connection is accepted.
        - -
        {@link android.bluetooth.BluetoothClass}
        +connection is accepted. + +
        {@link android.bluetooth.BluetoothClass}
        Describes the general characteristics and capabilities of a Bluetooth device. This is a read-only set of properties that define the device's major and minor device classes and its services. However, this does not reliably describe all Bluetooth profiles and services supported by the device, but is useful as a -hint to the device type.
        - +hint to the device type. +
        {@link android.bluetooth.BluetoothProfile}
        An interface that represents a Bluetooth profile. A Bluetooth profile is a wireless interface specification for Bluetooth-based communication between devices. An example is the Hands-Free profile. For more discussion of profiles, see Working with Profiles
        +href="#Profiles">Working with Profiles
        {@link android.bluetooth.BluetoothHeadset}
        Provides support for Bluetooth headsets to be used with mobile phones. This includes both Bluetooth -Headset and Hands-Free (v1.5) profiles.
        +Headset and Hands-Free (v1.5) profiles.
        {@link android.bluetooth.BluetoothA2dp}
        Defines how high quality audio can be streamed from one device to another over a Bluetooth connection. -"A2DP" stands for Advanced Audio Distribution Profile.
        +"A2DP" stands for Advanced Audio Distribution Profile.
        {@link android.bluetooth.BluetoothHealth}
        Represents a Health Device Profile proxy that controls the Bluetooth service.
        @@ -146,23 +146,23 @@ application’s registration state and Bluetooth channel state.
        {@link android.bluetooth.BluetoothHealthAppConfiguration}
        -
        Represents an application configuration that the Bluetooth Health third-party +
        Represents an application configuration that the Bluetooth Health third-party application registers to communicate with a remote Bluetooth health -device.
        +device.
        {@link android.bluetooth.BluetoothProfile.ServiceListener}
        An interface that notifies {@link android.bluetooth.BluetoothProfile} IPC clients when they have been connected to or disconnected from the service (that is, the internal service that runs a particular profile).
        - - - - - - -

        Bluetooth Permissions

        - + + + + + + +

        Bluetooth Permissions

        +

        In order to use Bluetooth features in your application, you must declare the Bluetooth permission {@link android.Manifest.permission#BLUETOOTH}. You need this permission to perform any Bluetooth communication, @@ -175,40 +175,40 @@ ability to discover local Bluetooth devices. The other abilities granted by this permission should not be used, unless the application is a "power manager" that will modify Bluetooth settings upon user request. Note: If you use {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission, then you must -also have the {@link android.Manifest.permission#BLUETOOTH} permission.

        - +also have the {@link android.Manifest.permission#BLUETOOTH} permission.

        +

        Declare the Bluetooth permission(s) in your application manifest file. For -example:

        - -
         
        +example:

        + +
         <manifest ... >
           <uses-permission android:name="android.permission.BLUETOOTH" />
           ...
         </manifest>
        -
        - +
        +

        See the <uses-permission> -reference for more information about declaring application permissions.

        - - -

        Setting Up Bluetooth

        - -
        - +href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><uses-permission> +reference for more information about declaring application permissions.

        + + +

        Setting Up Bluetooth

        + +
        + Figure 1: The enabling Bluetooth dialog. -
        - +
        +

        Before your application can communicate over Bluetooth, you need to verify -that Bluetooth is supported on the device, and if so, ensure that it is enabled.

        - +that Bluetooth is supported on the device, and if so, ensure that it is enabled.

        +

        If Bluetooth is not supported, then you should gracefully disable any Bluetooth features. If Bluetooth is supported, but disabled, then you can request that the user enable Bluetooth without leaving your application. This setup is -accomplished in two steps, using the {@link android.bluetooth.BluetoothAdapter}.

        - - -
          +accomplished in two steps, using the {@link android.bluetooth.BluetoothAdapter}.

          + + +
          1. Get the {@link android.bluetooth.BluetoothAdapter}

            The {@link android.bluetooth.BluetoothAdapter} is required for any and all Bluetooth activity. To get the {@link android.bluetooth.BluetoothAdapter}, call the static {@link @@ -217,15 +217,15 @@ android.bluetooth.BluetoothAdapter#getDefaultAdapter()} method. This returns a Bluetooth adapter (the Bluetooth radio). There's one Bluetooth adapter for the entire system, and your application can interact with it using this object. If {@link android.bluetooth.BluetoothAdapter#getDefaultAdapter()} returns null, -then the device does not support Bluetooth and your story ends here. For example:

            -
             
            +then the device does not support Bluetooth and your story ends here. For example:

            +
             BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
             if (mBluetoothAdapter == null) {
                 // Device does not support Bluetooth
             }
            -
            -
          2. - + + +
          3. Enable Bluetooth

            Next, you need to ensure that Bluetooth is enabled. Call {@link android.bluetooth.BluetoothAdapter#isEnabled()} to check whether Bluetooth is @@ -234,17 +234,17 @@ request that Bluetooth be enabled, call {@link android.app.Activity#startActivityForResult(Intent,int) startActivityForResult()} with the {@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_ENABLE} action Intent. This will issue a request to enable Bluetooth through the system settings (without -stopping your application). For example:

            -
             
            +stopping your application). For example:

            +
             if (!mBluetoothAdapter.isEnabled()) {
                 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
             }
            -
            - +
            +

            A dialog will appear requesting user permission to enable Bluetooth, as shown in Figure 1. If the user responds "Yes," the system will begin to enable Bluetooth -and focus will return to your application once the process completes (or fails).

            +and focus will return to your application once the process completes (or fails).

            The {@code REQUEST_ENABLE_BT} constant passed to {@link android.app.Activity#startActivityForResult(Intent,int) startActivityForResult()} is a locally @@ -259,9 +259,9 @@ android.app.Activity#onActivityResult(int,int,Intent) onActivityResult()} callback. If Bluetooth was not enabled due to an error (or the user responded "No") then the result code is {@link android.app.Activity#RESULT_CANCELED}.

            -
          4. -
          - + +
        +

        Optionally, your application can also listen for the {@link android.bluetooth.BluetoothAdapter#ACTION_STATE_CHANGED} broadcast Intent, which the system will broadcast whenever the Bluetooth state has changed. This broadcast contains @@ -273,21 +273,21 @@ android.bluetooth.BluetoothAdapter#STATE_ON}, {@link android.bluetooth.BluetoothAdapter#STATE_TURNING_OFF}, and {@link android.bluetooth.BluetoothAdapter#STATE_OFF}. Listening for this broadcast can be useful to detect changes made to the Bluetooth state while your -app is running.

        - +app is running.

        +

        Tip: Enabling discoverability will automatically enable Bluetooth. If you plan to consistently enable device discoverability before performing Bluetooth activity, you can skip step 2 above. Read about enabling discoverability, -below.

        - - -

        Finding Devices

        - +below.

        + + +

        Finding Devices

        +

        Using the {@link android.bluetooth.BluetoothAdapter}, you can find remote Bluetooth devices either through device discovery or by querying the list of paired (bonded) -devices.

        - +devices.

        +

        Device discovery is a scanning procedure that searches the local area for Bluetooth enabled devices and then requesting some information about each one (this is sometimes referred to as "discovering," "inquiring" or "scanning"). @@ -296,15 +296,15 @@ request only if it is currently enabled to be discoverable. If a device is discoverable, it will respond to the discovery request by sharing some information, such as the device name, class, and its unique MAC address. Using this information, the device performing discovery can then choose to initiate a -connection to the discovered device.

        - +connection to the discovered device.

        +

        Once a connection is made with a remote device for the first time, a pairing request is automatically presented to the user. When a device is paired, the basic information about that device (such as the device name, class, and MAC address) is saved and can be read using the Bluetooth APIs. Using the known MAC address for a remote device, a connection can be initiated with it at -any time without performing discovery (assuming the device is within range).

        - +any time without performing discovery (assuming the device is within range).

        +

        Remember there is a difference between being paired and being connected. To be paired means that two devices are aware of each other's existence, have a shared link-key that can be used for authentication, and are capable of @@ -312,28 +312,28 @@ establishing an encrypted connection with each other. To be connected means that the devices currently share an RFCOMM channel and are able to transmit data with each other. The current Android Bluetooth API's require devices to be paired before an RFCOMM connection can be established. (Pairing is automatically performed -when you initiate an encrypted connection with the Bluetooth APIs.)

        - +when you initiate an encrypted connection with the Bluetooth APIs.)

        +

        The following sections describe how to find devices that have been paired, or -discover new devices using device discovery.

        - +discover new devices using device discovery.

        +

        Note: Android-powered devices are not discoverable by default. A user can make the device discoverable for a limited time through the system settings, or an application can request that the user enable discoverability without leaving the -application. How to enable discoverability -is discussed below.

        - - -

        Querying paired devices

        - +application. How to enable discoverability +is discussed below.

        + + +

        Querying paired devices

        +

        Before performing device discovery, its worth querying the set of paired devices to see if the desired device is already known. To do so, call {@link android.bluetooth.BluetoothAdapter#getBondedDevices()}. This will return a Set of {@link android.bluetooth.BluetoothDevice}s representing paired devices. For example, you can query all paired devices and then -show the name of each device to the user, using an ArrayAdapter:

        -
         
        +show the name of each device to the user, using an ArrayAdapter:

        +
         Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
         // If there are paired devices
         if (pairedDevices.size() > 0) {
        @@ -343,24 +343,24 @@ if (pairedDevices.size() > 0) {
                 mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
             }
         }
        -
        - +
        +

        All that's needed from the {@link android.bluetooth.BluetoothDevice} object in order to initiate a connection is the MAC address. In this example, it's saved as a part of an ArrayAdapter that's shown to the user. The MAC address can later be extracted in order to initiate the connection. You can learn more about creating -a connection in the section about Connecting Devices.

        - - -

        Discovering devices

        - +a connection in the section about Connecting Devices.

        + + +

        Discovering devices

        +

        To start discovering devices, simply call {@link android.bluetooth.BluetoothAdapter#startDiscovery()}. The process is asynchronous and the method will immediately return with a boolean indicating whether discovery has successfully started. The discovery process usually involves an inquiry scan of about 12 seconds, followed by a page scan of -each found device to retrieve its Bluetooth name.

        - +each found device to retrieve its Bluetooth name.

        +

        Your application must register a BroadcastReceiver for the {@link android.bluetooth.BluetoothDevice#ACTION_FOUND} Intent in order to receive information about each @@ -371,8 +371,8 @@ Intent carries the extra fields {@link android.bluetooth.BluetoothDevice#EXTRA_CLASS}, containing a {@link android.bluetooth.BluetoothDevice} and a {@link android.bluetooth.BluetoothClass}, respectively. For example, here's how you can -register to handle the broadcast when devices are discovered:

        -
         
        +register to handle the broadcast when devices are discovered:

        +
         // Create a BroadcastReceiver for ACTION_FOUND
         private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
             public void onReceive(Context context, Intent intent) {
        @@ -389,15 +389,15 @@ private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
         // Register the BroadcastReceiver
         IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
         registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
        -
        - +
        +

        All that's needed from the {@link android.bluetooth.BluetoothDevice} object in order to initiate a connection is the MAC address. In this example, it's saved as a part of an ArrayAdapter that's shown to the user. The MAC address can later be extracted in order to initiate the connection. You can learn more about creating a connection -in the section about Connecting Devices.

        - +in the section about Connecting Devices.

        +

        Caution: Performing device discovery is a heavy procedure for the Bluetooth adapter and will consume a lot of its resources. Once you have found a device to @@ -406,10 +406,10 @@ connect, be certain that you always stop discovery with attempting a connection. Also, if you already hold a connection with a device, then performing discovery can significantly reduce the bandwidth available for the connection, so you should -not perform discovery while connected.

        - -

        Enabling discoverability

        - +not perform discovery while connected.

        + +

        Enabling discoverability

        +

        If you would like to make the local device discoverable to other devices, call {@link android.app.Activity#startActivityForResult(Intent,int)} with the {@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_DISCOVERABLE} action @@ -420,30 +420,30 @@ discoverable for 120 seconds. You can define a different duration by adding the extra. The maximum duration an app can set is 3600 seconds, and a value of 0 means the device is always discoverable. Any value below 0 or above 3600 is automatically set to 120 secs). For example, this snippet sets the duration to -300:

        +300:

        Intent discoverableIntent = new
         Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
         discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
         startActivity(discoverableIntent);
        -
        - -
        - + + +
        + Figure 2: The enabling discoverability dialog. -
        - +
        +

        A dialog will be displayed, requesting user permission to make the device discoverable, as shown in Figure 2. If the user responds "Yes," then the device will become discoverable for the specified amount of time. Your activity will then receive a call to the {@link android.app.Activity#onActivityResult(int,int,Intent) onActivityResult())} callback, with the result code equal to the duration that the device is discoverable. If the user responded "No" or if an error occurred, the result code will -be {@link android.app.Activity#RESULT_CANCELED}.

        - +be {@link android.app.Activity#RESULT_CANCELED}.

        +

        Note: If Bluetooth has not been enabled on the device, -then enabling device discoverability will automatically enable Bluetooth.

        - +then enabling device discoverability will automatically enable Bluetooth.

        +

        The device will silently remain in discoverable mode for the allotted time. If you would like to be notified when the discoverable mode has changed, you can register a BroadcastReceiver for the {@link @@ -457,18 +457,18 @@ new and old scan mode, respectively. Possible values for each are android.bluetooth.BluetoothAdapter#SCAN_MODE_NONE}, which indicate that the device is either in discoverable mode, not in discoverable mode but still able to receive connections, or not in discoverable -mode and unable to receive connections, respectively.

        - +mode and unable to receive connections, respectively.

        +

        You do not need to enable device discoverability if you will be initiating the connection to a remote device. Enabling discoverability is only necessary when you want your application to host a server socket that will accept incoming connections, because the remote devices must be able to discover the device -before it can initiate the connection.

        - - - -

        Connecting Devices

        - +before it can initiate the connection.

        + + + +

        Connecting Devices

        +

        In order to create a connection between your application on two devices, you must implement both the server-side and client-side mechanisms, because one device must open a server socket and the other one must initiate the connection @@ -478,36 +478,36 @@ client are considered connected to each other when they each have a connected point, each device can obtain input and output streams and data transfer can begin, which is discussed in the section about Managing a Connection. This section describes how -to initiate the connection between two devices.

        - +to initiate the connection between two devices.

        +

        The server device and the client device each obtain the required {@link android.bluetooth.BluetoothSocket} in different ways. The server will receive it when an incoming connection is accepted. The client will receive it when it -opens an RFCOMM channel to the server.

        - -
        - +opens an RFCOMM channel to the server.

        + +
        + Figure 3: The Bluetooth pairing dialog. -
        - +
        +

        One implementation technique is to automatically prepare each device as a server, so that each one has a server socket open and listening for connections. Then either device can initiate a connection with the other and become the client. Alternatively, one device can explicitly "host" the connection and open a server socket on demand and the other device can simply initiate the -connection.

        - +connection.

        +

        Note: If the two devices have not been previously paired, then the Android framework will automatically show a pairing request notification or dialog to the user during the connection procedure, as shown in Figure 3. So when attempting to connect devices, your application does not need to be concerned about whether or not the devices are paired. Your RFCOMM connection attempt will block until the user has successfully paired, -or will fail if the user rejects pairing, or if pairing fails or times out.

        - - -

        Connecting as a server

        - +or will fail if the user rejects pairing, or if pairing fails or times out.

        + + +

        Connecting as a server

        +

        When you want to connect two devices, one must act as a server by holding an open {@link android.bluetooth.BluetoothServerSocket}. The purpose of the server socket is to listen for incoming connection requests and when one is accepted, @@ -515,26 +515,26 @@ provide a connected {@link android.bluetooth.BluetoothSocket}. When the {@link android.bluetooth.BluetoothSocket} is acquired from the {@link android.bluetooth.BluetoothServerSocket}, the {@link android.bluetooth.BluetoothServerSocket} can (and should) be -discarded, unless you want to accept more connections.

        - - +

        Here's the basic procedure to set up a server socket and accept a -connection:

        - -
          +connection:

          + +
          1. Get a {@link android.bluetooth.BluetoothServerSocket} by calling the {@link android.bluetooth.BluetoothAdapter#listenUsingRfcommWithServiceRecord(String, @@ -546,9 +546,9 @@ UUID is also included in the SDP entry and will be the basis for the connection agreement with the client device. That is, when the client attempts to connect with this device, it will carry a UUID that uniquely identifies the service with which it wants to connect. These UUIDs must match in order for the connection to -be accepted (in the next step).

            -
          2. - +be accepted (in the next step).

            + +
          3. Start listening for connection requests by calling {@link android.bluetooth.BluetoothServerSocket#accept()}.

            This is a blocking call. It will return when either a connection has been @@ -556,9 +556,9 @@ accepted or an exception has occurred. A connection is accepted only when a remote device has sent a connection request with a UUID matching the one registered with this listening server socket. When successful, {@link android.bluetooth.BluetoothServerSocket#accept()} will -return a connected {@link android.bluetooth.BluetoothSocket}.

            -
          4. - +return a connected {@link android.bluetooth.BluetoothSocket}.

            + +
          5. Unless you want to accept additional connections, call {@link android.bluetooth.BluetoothServerSocket#close()}.

            This releases the server socket and all its resources, but does not close the @@ -567,10 +567,10 @@ android.bluetooth.BluetoothServerSocket#accept()}. Unlike TCP/IP, RFCOMM only al connected client per channel at a time, so in most cases it makes sense to call {@link android.bluetooth.BluetoothServerSocket#close()} on the {@link android.bluetooth.BluetoothServerSocket} immediately after accepting a connected -socket.

            -
          6. -
          - +socket.

          + +
        +

        The {@link android.bluetooth.BluetoothServerSocket#accept()} call should not be executed in the main activity UI thread because it is a blocking call and will prevent any other interaction with the application. It usually makes @@ -583,16 +583,16 @@ android.bluetooth.BluetoothServerSocket} (or {@link android.bluetooth.BluetoothSocket}) from another thread and the blocked call will immediately return. Note that all methods on a {@link android.bluetooth.BluetoothServerSocket} or {@link android.bluetooth.BluetoothSocket} -are thread-safe.

        - -

        Example

        - +are thread-safe.

        + +

        Example

        +

        Here's a simplified thread for the server component that accepts incoming -connections:

        -
         
        +connections:

        +
         private class AcceptThread extends Thread {
             private final BluetoothServerSocket mmServerSocket;
        - 
        +
             public AcceptThread() {
                 // Use a temporary object that is later assigned to mmServerSocket,
                 // because mmServerSocket is final
        @@ -603,7 +603,7 @@ private class AcceptThread extends Thread {
                 } catch (IOException e) { }
                 mmServerSocket = tmp;
             }
        - 
        +
             public void run() {
                 BluetoothSocket socket = null;
                 // Keep listening until exception occurs or a socket is returned
        @@ -622,7 +622,7 @@ private class AcceptThread extends Thread {
                     }
                 }
             }
        - 
        +
             /** Will cancel the listening socket, and cause the thread to finish */
             public void cancel() {
                 try {
        @@ -630,37 +630,37 @@ private class AcceptThread extends Thread {
                 } catch (IOException e) { }
             }
         }
        -
        - +
        +

        In this example, only one incoming connection is desired, so as soon as a connection is accepted and the {@link android.bluetooth.BluetoothSocket} is acquired, the application sends the acquired {@link android.bluetooth.BluetoothSocket} to a separate thread, closes the -{@link android.bluetooth.BluetoothServerSocket} and breaks the loop.

        - +{@link android.bluetooth.BluetoothServerSocket} and breaks the loop.

        +

        Note that when {@link android.bluetooth.BluetoothServerSocket#accept()} returns the {@link android.bluetooth.BluetoothSocket}, the socket is already connected, so you should not call {@link android.bluetooth.BluetoothSocket#connect()} (as you do from the -client-side).

        - +client-side).

        +

        manageConnectedSocket() is a fictional method in the application that will initiate the thread for transferring data, which is discussed in the section -about Managing a Connection.

        - +about Managing a Connection.

        +

        You should usually close your {@link android.bluetooth.BluetoothServerSocket} as soon as you are done listening for incoming connections. In this example, {@link android.bluetooth.BluetoothServerSocket#close()} is called as soon as the {@link android.bluetooth.BluetoothSocket} is acquired. You may also want to provide a public method in your thread that can close the private {@link android.bluetooth.BluetoothSocket} in the event that you need to stop listening on the -server socket.

        - - -

        Connecting as a client

        - +server socket.

        + + +

        Connecting as a client

        +

        In order to initiate a connection with a remote device (a device holding an open server socket), you must first obtain a {@link @@ -669,11 +669,11 @@ android.bluetooth.BluetoothDevice} object that represents the remote device. section about Finding Devices.) You must then use the {@link android.bluetooth.BluetoothDevice} to acquire a {@link -android.bluetooth.BluetoothSocket} and initiate the connection.

        - -

        Here's the basic procedure:

        - -
          +android.bluetooth.BluetoothSocket} and initiate the connection.

          + +

          Here's the basic procedure:

          + +
          1. Using the {@link android.bluetooth.BluetoothDevice}, get a {@link android.bluetooth.BluetoothSocket} by calling {@link android.bluetooth.BluetoothDevice#createRfcommSocketToServiceRecord(UUID)}. @@ -684,9 +684,9 @@ must match the UUID used by the server device when it opened its android.bluetooth.BluetoothAdapter#listenUsingRfcommWithServiceRecord(String, UUID)}). Using the same UUID is simply a matter of hard-coding the UUID string into your application and then referencing it from both the server and client -code.

            -
          2. - +code.

            + +
          3. Initiate the connection by calling {@link android.bluetooth.BluetoothSocket#connect()}.

            Upon this call, the system will perform an SDP lookup on the remote device in @@ -697,34 +697,34 @@ android.bluetooth.BluetoothSocket#connect()} will return. This method is a blocking call. If, for any reason, the connection fails or the {@link android.bluetooth.BluetoothSocket#connect()} method times out (after about -12 seconds), then it will throw an exception.

            +12 seconds), then it will throw an exception.

            Because {@link android.bluetooth.BluetoothSocket#connect()} is a blocking call, this connection procedure should always be performed in a thread separate from the main activity -thread.

            +thread.

            Note: You should always ensure that the device is not performing device discovery when you call {@link android.bluetooth.BluetoothSocket#connect()}. If discovery is in progress, then the -connection attempt will be significantly slowed and is more likely to fail.

            -
          4. -
          - -

          Example

          - +connection attempt will be significantly slowed and is more likely to fail.

          + +
        + +

        Example

        +

        Here is a basic example of a thread that initiates a Bluetooth -connection:

        -
         
        +connection:

        +
         private class ConnectThread extends Thread {
             private final BluetoothSocket mmSocket;
             private final BluetoothDevice mmDevice;
        - 
        +
             public ConnectThread(BluetoothDevice device) {
                 // Use a temporary object that is later assigned to mmSocket,
                 // because mmSocket is final
                 BluetoothSocket tmp = null;
                 mmDevice = device;
        - 
        +
                 // Get a BluetoothSocket to connect with the given BluetoothDevice
                 try {
                     // MY_UUID is the app's UUID string, also used by the server code
        @@ -732,11 +732,11 @@ private class ConnectThread extends Thread {
                 } catch (IOException e) { }
                 mmSocket = tmp;
             }
        - 
        +
             public void run() {
                 // Cancel discovery because it will slow down the connection
                 mBluetoothAdapter.cancelDiscovery();
        - 
        +
                 try {
                     // Connect the device through the socket. This will block
                     // until it succeeds or throws an exception
        @@ -748,11 +748,11 @@ private class ConnectThread extends Thread {
                     } catch (IOException closeException) { }
                     return;
                 }
        - 
        +
                 // Do work to manage the connection (in a separate thread)
                 manageConnectedSocket(mmSocket);
             }
        - 
        +
             /** Will cancel an in-progress connection, and close the socket */
             public void cancel() {
                 try {
        @@ -760,42 +760,42 @@ private class ConnectThread extends Thread {
                 } catch (IOException e) { }
             }
         }
        -
        - +
        +

        Notice that {@link android.bluetooth.BluetoothAdapter#cancelDiscovery()} is called before the connection is made. You should always do this before connecting and it is safe to call without actually checking whether it is running or not (but if you do want to -check, call {@link android.bluetooth.BluetoothAdapter#isDiscovering()}).

        - +check, call {@link android.bluetooth.BluetoothAdapter#isDiscovering()}).

        +

        manageConnectedSocket() is a fictional method in the application that will initiate the thread for transferring data, which is discussed in the section -about Managing a Connection.

        - +about Managing a Connection.

        +

        When you're done with your {@link android.bluetooth.BluetoothSocket}, always call {@link android.bluetooth.BluetoothSocket#close()} to clean up. Doing so will immediately close the connected socket and clean up all internal -resources.

        - - -

        Managing a Connection

        - +resources.

        + + +

        Managing a Connection

        +

        When you have successfully connected two (or more) devices, each one will have a connected {@link android.bluetooth.BluetoothSocket}. This is where the fun begins because you can share data between devices. Using the {@link android.bluetooth.BluetoothSocket}, the general procedure to transfer arbitrary data is -simple:

        -
          +simple:

          +
          1. Get the {@link java.io.InputStream} and {@link java.io.OutputStream} that handle transmissions through the socket, via {@link android.bluetooth.BluetoothSocket#getInputStream()} and -{@link android.bluetooth.BluetoothSocket#getOutputStream}, respectively.
          2. - +{@link android.bluetooth.BluetoothSocket#getOutputStream}, respectively. +
          3. Read and write data to the streams with {@link -java.io.InputStream#read(byte[])} and {@link java.io.OutputStream#write(byte[])}.
          4. -
          - -

          That's it.

          - +java.io.InputStream#read(byte[])} and {@link java.io.OutputStream#write(byte[])}. +
        + +

        That's it.

        +

        There are, of course, implementation details to consider. First and foremost, you should use a dedicated thread for all stream reading and writing. This is important because both {@link java.io.InputStream#read(byte[])} and {@link @@ -806,37 +806,37 @@ block, but can block for flow control if the remote device is not calling {@link java.io.InputStream#read(byte[])} quickly enough and the intermediate buffers are full. So, your main loop in the thread should be dedicated to reading from the {@link java.io.InputStream}. A separate public method in the thread can be used to initiate -writes to the {@link java.io.OutputStream}.

        - -

        Example

        - -

        Here's an example of how this might look:

        -
         
        +writes to the {@link java.io.OutputStream}.

        + +

        Example

        + +

        Here's an example of how this might look:

        +
         private class ConnectedThread extends Thread {
             private final BluetoothSocket mmSocket;
             private final InputStream mmInStream;
             private final OutputStream mmOutStream;
        - 
        +
             public ConnectedThread(BluetoothSocket socket) {
                 mmSocket = socket;
                 InputStream tmpIn = null;
                 OutputStream tmpOut = null;
        - 
        +
                 // Get the input and output streams, using temp objects because
                 // member streams are final
                 try {
                     tmpIn = socket.getInputStream();
                     tmpOut = socket.getOutputStream();
                 } catch (IOException e) { }
        - 
        +
                 mmInStream = tmpIn;
                 mmOutStream = tmpOut;
             }
        - 
        +
             public void run() {
                 byte[] buffer = new byte[1024];  // buffer store for the stream
                 int bytes; // bytes returned from read()
        - 
        +
                 // Keep listening to the InputStream until an exception occurs
                 while (true) {
                     try {
        @@ -850,14 +850,14 @@ private class ConnectedThread extends Thread {
                     }
                 }
             }
        - 
        +
             /* Call this from the main activity to send data to the remote device */
             public void write(byte[] bytes) {
                 try {
                     mmOutStream.write(bytes);
                 } catch (IOException e) { }
             }
        - 
        +
             /* Call this from the main activity to shutdown the connection */
             public void cancel() {
                 try {
        @@ -865,44 +865,44 @@ private class ConnectedThread extends Thread {
                 } catch (IOException e) { }
             }
         }
        -
        - +
        +

        The constructor acquires the necessary streams and once executed, the thread will wait for data to come through the InputStream. When {@link java.io.InputStream#read(byte[])} returns with bytes from the stream, the data is sent to the main activity using a member Handler from the parent class. Then it goes back and waits for more bytes from -the stream.

        - +the stream.

        +

        Sending outgoing data is as simple as calling the thread's write() method from the main activity and passing in the bytes to be sent. This method then simply calls {@link -java.io.OutputStream#write(byte[])} to send the data to the remote device.

        - +java.io.OutputStream#write(byte[])} to send the data to the remote device.

        +

        The thread's cancel() method is important so that the connection can be terminated at any time by closing the {@link android.bluetooth.BluetoothSocket}. This should always be called when you're done using the Bluetooth -connection.

        - -
        -

        For a demonstration of using the Bluetooth APIs, see the Bluetooth Chat sample app.

        -
        +connection.

        -

        Working with Profiles

        +
        +

        For a demonstration of using the Bluetooth APIs, see the Bluetooth Chat sample app.

        +
        + +

        Working with Profiles

        Starting in Android 3.0, the Bluetooth API includes support for working with Bluetooth profiles. A Bluetooth profile is a wireless interface specification for Bluetooth-based communication between devices. An example is the Hands-Free profile. For a mobile phone to connect to a wireless headset, -both devices must support the Hands-Free profile.

        +both devices must support the Hands-Free profile.

        You can implement the interface {@link android.bluetooth.BluetoothProfile} to write your own classes to support a particular Bluetooth profile. The Android Bluetooth API provides implementations for the following Bluetooth -profiles:

        - -

        Here are the basic steps for working with a profile:

        -
          +

          Here are the basic steps for working with a profile:

          +
          1. Get the default adapter, as described in Setting Up - Bluetooth.
          2. + Bluetooth.
          3. Use {@link android.bluetooth.BluetoothAdapter#getProfileProxy(android.content.Context, android.bluetooth.BluetoothProfile.ServiceListener, int) getProfileProxy()} to establish a connection to the profile proxy object associated with the profile. In the example below, the profile proxy object is an instance of {@link -android.bluetooth.BluetoothHeadset}.
          4. +android.bluetooth.BluetoothHeadset}.
          5. Set up a {@link android.bluetooth.BluetoothProfile.ServiceListener}. This listener notifies {@link android.bluetooth.BluetoothProfile} IPC clients when -they have been connected to or disconnected from the service.
          6. +they have been connected to or disconnected from the service.
          7. In {@link android.bluetooth.BluetoothProfile.ServiceListener#onServiceConnected(int, android.bluetooth.BluetoothProfile) onServiceConnected()}, get a handle -to the profile proxy object.
          8. +to the profile proxy object.
          9. Once you have the profile proxy object, you can use it to monitor the state of the connection and perform other operations that are relevant to that -profile.
          10. -
          +profile. +

        For example, this code snippet shows how to connect to a {@link android.bluetooth.BluetoothHeadset} proxy object so that you can control the -Headset profile:

        +Headset profile:

        BluetoothHeadset mBluetoothHeadset;
        - 
        +
         // Get the default adapter
         BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        - 
        +
         // Establish connection to the proxy.
         mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET);
        - 
        +
         private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
             public void onServiceConnected(int profile, BluetoothProfile proxy) {
                 if (profile == BluetoothProfile.HEADSET) {
        @@ -984,16 +984,16 @@ private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile
                 }
             }
         };
        - 
        +
         // ... call functions on mBluetoothHeadset
        - 
        +
         // Close proxy connection after use.
         mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset);
        -
        + -

        Vendor-specific AT commands

        +

        Vendor-specific AT commands

        Starting in Android 3.0, applications can register to receive system broadcasts of pre-defined vendor-specific AT commands sent by headsets (such as @@ -1060,7 +1060,7 @@ android.bluetooth.BluetoothProfile.ServiceListener#HEALTH} profile type to establish a connection with the profile proxy object.

      • Create a {@link android.bluetooth.BluetoothHealthCallback} and register an -application configuration +application configuration ({@link android.bluetooth.BluetoothHealthAppConfiguration}) that acts as a health sink.
      • diff --git a/docs/html/guide/topics/connectivity/nfc/index.jd b/docs/html/guide/topics/connectivity/nfc/index.jd index f12facf75ecc2..bc4f075c71f75 100644 --- a/docs/html/guide/topics/connectivity/nfc/index.jd +++ b/docs/html/guide/topics/connectivity/nfc/index.jd @@ -17,12 +17,12 @@ page.title=Near Field Communication

        Android-powered devices with NFC simultaneously support three main modes of operation:

          -
        1. Reader/writer mode, allowing the NFC device to read and/or write +
        2. Reader/writer mode, allowing the NFC device to read and/or write passive NFC tags and stickers.
        3. -
        4. P2P mode, allowing the NFC device to exchange data with other NFC +
        5. P2P mode, allowing the NFC device to exchange data with other NFC peers; this operation mode is used by Android Beam.
        6. -
        7. Card emulation mode, allowing the NFC device itself to act as an NFC -card. The emulated NFC card can then be accessed by an external NFC reader, +
        8. Card emulation mode, allowing the NFC device itself to act as an NFC +card. The emulated NFC card can then be accessed by an external NFC reader, such as an NFC point-of-sale terminal.
        diff --git a/docs/html/guide/topics/connectivity/sip.jd b/docs/html/guide/topics/connectivity/sip.jd index d754894741e7f..d8d6d277bbf99 100755 --- a/docs/html/guide/topics/connectivity/sip.jd +++ b/docs/html/guide/topics/connectivity/sip.jd @@ -12,10 +12,10 @@ page.tags=sipmanager,sipprofile,sipaudiocall,telephony
      • Creating a SIP Manager
      • Registering with a SIP Server
      • Making an Audio Call
      • -
      • Receiving Calls
      • +
      • Receiving Calls
      • Testing SIP Applications
      • - +

        Key classes

        1. {@link android.net.sip.SipManager}
        2. @@ -23,7 +23,7 @@ page.tags=sipmanager,sipprofile,sipaudiocall,telephony
        3. {@link android.net.sip.SipAudioCall}
        - +

        Related samples

        1. SipDemo
        2. @@ -46,9 +46,9 @@ record or playback directly.

          Requirements and Limitations

          Here are the requirements for developing a SIP application:

            - +
          • You must have a mobile device that is running Android 2.3 or higher.
          • - +
          • SIP runs over a wireless data connection, so your device must have a data connection (with a mobile data service or Wi-Fi). This means that you can't test on AVD—you can only test on a physical device. For details, see @@ -139,7 +139,7 @@ capable of supporting SIP, add the following to your application's manifest:

              -
            • <uses-sdk android:minSdkVersion="9" />. This +
            • <uses-sdk android:minSdkVersion="9" />. This indicates that your application requires Android 2.3 or higher. For more information, see API Levels and the documentation for the <uses- feature> element.
            • - +

            If your application is designed to receive calls, you must also define a receiver ({@link android.content.BroadcastReceiver} subclass) in the application's manifest:

            @@ -261,7 +261,7 @@ public void onRegistering(String localProfileUri) { public void onRegistrationDone(String localProfileUri, long expiryTime) { updateStatus("Ready"); } - + public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage) { updateStatus("Registration failed. Please check settings."); @@ -291,8 +291,8 @@ example:

          • A {@link android.net.sip.SipProfile} that is making the call (the "local profile"), and a valid SIP address to receive the call (the -"peer profile"). - +"peer profile"). +
          • A {@link android.net.sip.SipManager} object.
          @@ -304,7 +304,7 @@ established:

           SipAudioCall.Listener listener = new SipAudioCall.Listener() {
          -  
          +
              @Override
              public void onCallEstablished(SipAudioCall call) {
                 call.startAudio();
          @@ -312,7 +312,7 @@ SipAudioCall.Listener listener = new SipAudioCall.Listener() {
                 call.toggleMute();
                    ...
              }
          -   
          +
              @Override
              public void onCallEnded(SipAudioCall call) {
                 // Do something.
          @@ -326,12 +326,12 @@ make the  call. The {@link android.net.sip.SipManager} method
           
          • A local SIP profile (the caller).
          • A peer SIP profile (the user being called).
          • - +
          • A {@link android.net.sip.SipAudioCall.Listener} to listen to the call events from {@link android.net.sip.SipAudioCall}. This can be null, but as shown above, the listener is used to set things up once the call is established.
          • - +
          • The timeout value, in seconds.

          For example:

          @@ -349,15 +349,15 @@ your application:

          <receiver>. In SipDemo, this is <receiver android:name=".IncomingCallReceiver" android:label="Call Receiver"/>. - +
        3. Implement the receiver, which is a subclass of {@link android.content.BroadcastReceiver}. In SipDemo, this is IncomingCallReceiver.
        4. - +
        5. Initialize the local profile ({@link android.net.sip.SipProfile}) with a pending intent that fires your receiver when someone calls the local profile.
        6. - +
        7. Set up an intent filter that filters by the action that represents an incoming call. In SipDemo, this action is android.SipDemo.INCOMING_CALL.
        8. @@ -427,16 +427,16 @@ action string provided by the application. In SipDemo, this action string is android.net.sip.SipProfile} object gets created with a pending intent based on the action string android.SipDemo.INCOMING_CALL. The PendingIntent object will perform a broadcast when the {@link -android.net.sip.SipProfile} receives a call:

          +android.net.sip.SipProfile} receives a call:

           public SipManager mSipManager = null;
           public SipProfile mSipProfile = null;
           ...
           
          -Intent intent = new Intent(); 
          -intent.setAction("android.SipDemo.INCOMING_CALL"); 
          -PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA); 
          +Intent intent = new Intent();
          +intent.setAction("android.SipDemo.INCOMING_CALL");
          +PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);
           mSipManager.open(mSipProfile, pendingIntent, null);

          The broadcast will be intercepted by the intent filter, which will then fire @@ -485,8 +485,8 @@ href="{@docRoot}tools/device.html">Developing on a Device. href="{@docRoot}tools/device.html">Developing on a Device.

        9. If you are using Android Studio, you can view the application log output by -opening the Event Log console (View > Tool Windows > Event Log). -
        10. Ensure your application is configured to launch Logcat automatically when it runs: +opening the Event Log console (View > Tool Windows > Event Log). +
        11. Ensure your application is configured to launch Logcat automatically when it runs:
          1. Select Run > Edit Configurations.
          2. Select the Miscellaneous tab in the Run/Debug Configurations window. diff --git a/docs/html/guide/topics/connectivity/usb/accessory.jd b/docs/html/guide/topics/connectivity/usb/accessory.jd index a2177678fc56d..3942b3a951b96 100644 --- a/docs/html/guide/topics/connectivity/usb/accessory.jd +++ b/docs/html/guide/topics/connectivity/usb/accessory.jd @@ -169,7 +169,7 @@ UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXT include a <uses-feature> element that declares that your application uses the android.hardware.usb.accessory feature.
          3. -
          4. If you are using the +
          5. If you are using the add-on library, add the <uses-library> element specifying com.android.future.usb.accessory for the library.
          6. @@ -347,7 +347,7 @@ UsbAccessory[] accessoryList = manager.getAcccessoryList(); private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"; private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { - + public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action)) { @@ -444,7 +444,7 @@ private void openAccessory() {
             BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
                 public void onReceive(Context context, Intent intent) {
            -        String action = intent.getAction(); 
            +        String action = intent.getAction();
             
                     if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
                         UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
            diff --git a/docs/html/guide/topics/connectivity/usb/host.jd b/docs/html/guide/topics/connectivity/usb/host.jd
            index d2194e6d6f6dd..856027d09d7f6 100644
            --- a/docs/html/guide/topics/connectivity/usb/host.jd
            +++ b/docs/html/guide/topics/connectivity/usb/host.jd
            @@ -263,7 +263,7 @@ UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE
               obtain a device from the map.

             UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
            -...  
            +...
             HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
             UsbDevice device = deviceList.get("deviceName");
             
            @@ -317,7 +317,7 @@ private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { if(device != null){ //call method to set up device communication } - } + } else { Log.d(TAG, "permission denied for device " + device); } @@ -396,7 +396,7 @@ private boolean forceClaim = true; UsbInterface intf = device.getInterface(0); UsbEndpoint endpoint = intf.getEndpoint(0); -UsbDeviceConnection connection = mUsbManager.openDevice(device); +UsbDeviceConnection connection = mUsbManager.openDevice(device); connection.claimInterface(intf, forceClaim); connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT); //do in another thread
            @@ -422,7 +422,7 @@ connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT); //do in another
             BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
                 public void onReceive(Context context, Intent intent) {
            -        String action = intent.getAction(); 
            +        String action = intent.getAction();
             
                   if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                         UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            diff --git a/docs/html/guide/topics/connectivity/wifip2p.jd b/docs/html/guide/topics/connectivity/wifip2p.jd
            index d7e1269696cf9..b8eb40ea5014f 100644
            --- a/docs/html/guide/topics/connectivity/wifip2p.jd
            +++ b/docs/html/guide/topics/connectivity/wifip2p.jd
            @@ -66,7 +66,7 @@ a photo sharing application.

            methods. A {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION} intent is also broadcast if the {@link android.net.wifi.p2p.WifiP2pManager#discoverPeers discoverPeers()} method discovers that the peers list has changed.

            - +

            API Overview

            The {@link android.net.wifi.p2p.WifiP2pManager} class provides methods to allow you to interact with @@ -135,7 +135,7 @@ a photo sharing application.

            are described in the following table:

            Table 2. Wi-Fi P2P Listeners

            - + @@ -395,7 +395,7 @@ protected void onPause() { available peers that are in range. The call to this function is asynchronous and a success or failure is communicated to your application with {@link android.net.wifi.p2p.WifiP2pManager.ActionListener#onSuccess onSuccess()} and {@link - android.net.wifi.p2p.WifiP2pManager.ActionListener#onFailure onFailure()} if you created a + android.net.wifi.p2p.WifiP2pManager.ActionListener#onFailure onFailure()} if you created a {@link android.net.wifi.p2p.WifiP2pManager.ActionListener}. The {@link android.net.wifi.p2p.WifiP2pManager.ActionListener#onSuccess onSuccess()} method only notifies you that the discovery process succeeded and does not provide any information about the actual peers diff --git a/docs/html/guide/topics/data/index.jd b/docs/html/guide/topics/data/index.jd index 1e082b3fef95f..169fc223d5556 100644 --- a/docs/html/guide/topics/data/index.jd +++ b/docs/html/guide/topics/data/index.jd @@ -1,6 +1,6 @@ page.title=Data Storage page.landing=true -page.landing.intro=Store application data in databases, files, or preferences, in internal or removeable storage. You can also add a data backup service to let users store and recover application and system data. +page.landing.intro=Store application data in databases, files, or preferences, in internal or removeable storage. You can also add a data backup service to let users store and recover application and system data. page.landing.image= @jd:body @@ -10,14 +10,14 @@ page.landing.image= \ No newline at end of file diff --git a/docs/html/guide/topics/graphics/index.jd b/docs/html/guide/topics/graphics/index.jd index 17f630994952f..a87e404503ed1 100644 --- a/docs/html/guide/topics/graphics/index.jd +++ b/docs/html/guide/topics/graphics/index.jd @@ -17,7 +17,7 @@ support hardware acceleration on tablets. With this new pipeline, all drawing op by the UI toolkit are carried out using the GPU. You’ll be happy to hear that Android 4.0, Ice Cream Sandwich, brings an improved version of the hardware-accelerated 2D rendering pipeline.

            - +

            Introducing ViewPropertyAnimator

            @@ -25,7 +25,7 @@ href="http://android-developers.blogspot.com/2011/05/introducing-viewpropertyani including the new properties added to the View class in 3.0. In the 3.1 release, we added a small utility class that makes animating these properties even easier.

            - +

            Android 3.0 Hardware Acceleration

            @@ -43,7 +43,7 @@ applications can benefit from an extra boost in performance.

            that keeps your user interface (UI) components responsive and avoids exceeding your application memory limit.

            - + \ No newline at end of file diff --git a/docs/html/guide/topics/graphics/overview.jd b/docs/html/guide/topics/graphics/overview.jd index 66a675dc6491b..98d80a0f51bf9 100644 --- a/docs/html/guide/topics/graphics/overview.jd +++ b/docs/html/guide/topics/graphics/overview.jd @@ -6,7 +6,7 @@ page.title=Animation and Graphics Overview and help you decide with approach is best for your needs.

            Animation

            - +

            The Android framework provides two animation systems: property animation and view animation. Both animation systems are viable options, but the property animation system, in general, is the preferred method to use, because it diff --git a/docs/html/guide/topics/graphics/prop-animation.jd b/docs/html/guide/topics/graphics/prop-animation.jd index aed533de16ca1..693799c5ba1e6 100755 --- a/docs/html/guide/topics/graphics/prop-animation.jd +++ b/docs/html/guide/topics/graphics/prop-animation.jd @@ -165,9 +165,9 @@ page.tags=valueanimator,objectanimator,layouttransition,ViewPropertyAnimator "{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/index.html">API Demos sample project provides many examples on how to use the property animation system.

            - +

            How Property Animation Differs from View Animation

            - +

            The view animation system provides the capability to only animate {@link android.view.View} objects, so if you wanted to animate non-{@link android.view.View} objects, you have to implement your own code to do so. The view animation system is also constrained in the fact that it only diff --git a/docs/html/guide/topics/location/strategies.jd b/docs/html/guide/topics/location/strategies.jd index 32be463e687cb..2dfed2ce6e8e4 100755 --- a/docs/html/guide/topics/location/strategies.jd +++ b/docs/html/guide/topics/location/strategies.jd @@ -411,12 +411,12 @@ data to work.

            Using Android Studio

            Select Tools > Android > AVD Manager. In the Android Virtual -Device Manager window, choose your AVD and launch it in the emulator by selecting the green +Device Manager window, choose your AVD and launch it in the emulator by selecting the green play arrow in the Actions column.

            Then, select Tools > Android > Android Device Monitor. -Select the Emulator Control tab in the Android Device Monitor window, and enter GPS coordinates -under Location Controls as individual lat/long coordinates, with a GPX file for route playback, +Select the Emulator Control tab in the Android Device Monitor window, and enter GPS coordinates +under Location Controls as individual lat/long coordinates, with a GPX file for route playback, or a KML file for multiple place marks.

            diff --git a/docs/html/guide/topics/manifest/action-element.jd b/docs/html/guide/topics/manifest/action-element.jd index fc6ce440579da..f3b340e2737ac 100644 --- a/docs/html/guide/topics/manifest/action-element.jd +++ b/docs/html/guide/topics/manifest/action-element.jd @@ -13,10 +13,10 @@ parent.link=manifest-intro.html

            description:
            Adds an action to an intent filter. -An <intent-filter> element must contain +An <intent-filter> element must contain one or more {@code } elements. If it doesn't contain any, no -Intent objects will get through the filter. See -Intents and +Intent objects will get through the filter. See +Intents and Intent Filters for details on intent filters and the role of action specifications within a filter.
            @@ -25,16 +25,16 @@ specifications within a filter.
            {@code android:name}
            The name of the action. Some standard actions are defined in the -{@link android.content.Intent#ACTION_CHOOSER Intent} class as +{@link android.content.Intent#ACTION_CHOOSER Intent} class as ACTION_string constants. To assign one of these actions to -this attribute, prepend "{@code android.intent.action.}" to the +this attribute, prepend "{@code android.intent.action.}" to the string that follows {@code ACTION_}. For example, for {@code ACTION_MAIN}, use "{@code android.intent.action.MAIN}" and for {@code ACTION_WEB_SEARCH}, use "{@code android.intent.action.WEB_SEARCH}".

            For actions you define, it's best to use the package name as a prefix to -ensure uniqueness. For example, a {@code TRANSMOGRIFY} action might be specified +ensure uniqueness. For example, a {@code TRANSMOGRIFY} action might be specified as follows:

            diff --git a/docs/html/guide/topics/manifest/activity-alias-element.jd b/docs/html/guide/topics/manifest/activity-alias-element.jd index 1427b55219bdc..adb9937899fd2 100644 --- a/docs/html/guide/topics/manifest/activity-alias-element.jd +++ b/docs/html/guide/topics/manifest/activity-alias-element.jd @@ -29,62 +29,62 @@ alias and it must be declared before the alias in the manifest.

            The alias presents the target activity as a independent entity. -It can have its own set of intent filters, and they, rather than the -intent filters on the target activity itself, determine which intents +It can have its own set of intent filters, and they, rather than the +intent filters on the target activity itself, determine which intents can activate the target through the alias and how the system -treats the alias. For example, the intent filters on the alias may -specify the "{@link android.content.Intent#ACTION_MAIN -android.intent.action.MAIN}" -and "{@link android.content.Intent#CATEGORY_LAUNCHER -android.intent.category.LAUNCHER}" flags, causing it to be -represented in the application launcher, even though none of the +treats the alias. For example, the intent filters on the alias may +specify the "{@link android.content.Intent#ACTION_MAIN +android.intent.action.MAIN}" +and "{@link android.content.Intent#CATEGORY_LAUNCHER +android.intent.category.LAUNCHER}" flags, causing it to be +represented in the application launcher, even though none of the filters on the target activity itself set these flags.

            With the exception of {@code targetActivity}, {@code } -attributes are a subset of <activity> attributes. +attributes are a subset of <activity> attributes. For attributes in the subset, none of the values set for the target carry over -to the alias. However, for attributes not in the subset, the values set for +to the alias. However, for attributes not in the subset, the values set for the target activity also apply to the alias.

            attributes:
            {@code android:enabled}
            -
            Whether or not the target activity can be instantiated by the system through -this alias — "{@code true}" if it can be, and "{@code false}" if not. +
            Whether or not the target activity can be instantiated by the system through +this alias — "{@code true}" if it can be, and "{@code false}" if not. The default value is "{@code true}".

            -The <application> element has its own -enabled attribute that applies to all -application components, including activity aliases. The +The <application> element has its own +enabled attribute that applies to all +application components, including activity aliases. The <application> and {@code } -attributes must both be "{@code true}" for the system to be able to instantiate -the target activity through the alias. If either is "{@code false}", the alias +attributes must both be "{@code true}" for the system to be able to instantiate +the target activity through the alias. If either is "{@code false}", the alias does not work.

            {@code android:exported}
            -
            Whether or not components of other applications can launch the target activity -through this alias — "{@code true}" if they can, and "{@code false}" if not. -If "{@code false}", the target activity can be launched through the alias only by -components of the same application as the alias or applications with the same user ID. +
            Whether or not components of other applications can launch the target activity +through this alias — "{@code true}" if they can, and "{@code false}" if not. +If "{@code false}", the target activity can be launched through the alias only by +components of the same application as the alias or applications with the same user ID.

            -The default value depends on whether the alias contains intent filters. The +The default value depends on whether the alias contains intent filters. The absence of any filters means that the activity can be invoked through the alias -only by specifying the exact name of the alias. This implies that the alias -is intended only for application-internal use (since others would not know its name) +only by specifying the exact name of the alias. This implies that the alias +is intended only for application-internal use (since others would not know its name) — so the default value is "{@code false}". -On the other hand, the presence of at least one filter implies that the alias +On the other hand, the presence of at least one filter implies that the alias is intended for external use — so the default value is "{@code true}".

            {@code android:icon}
            -
            An icon for the target activity when presented to users through the alias. -See the <activity> element's +
            An icon for the target activity when presented to users through the alias. +See the <activity> element's icon attribute for more information.
            {@code android:label}
            @@ -95,31 +95,31 @@ See the &l
            {@code android:name}
            A unique name for the alias. The name should resemble a fully -qualified class name. But, unlike the name of the target activity, -the alias name is arbitrary; it does not refer to an actual class. +qualified class name. But, unlike the name of the target activity, +the alias name is arbitrary; it does not refer to an actual class.

            {@code android:permission}
            -
            The name of a permission that clients must have to launch the target activity -or get it to do something via the alias. If a caller of +
            The name of a permission that clients must have to launch the target activity +or get it to do something via the alias. If a caller of {@link android.content.Context#startActivity startActivity()} or {@link android.app.Activity#startActivityForResult startActivityForResult()} has not been granted the specified permission, the target activity will not be -activated. +activated.

            This attribute supplants any permission set for the target activity itself. If it is not set, a permission is not needed to activate the target through the alias.

            -For more information on permissions, see the -Permissions +For more information on permissions, see the +Permissions section in the introduction.

            {@code android:targetActivity}
            The name of the activity that can be activated through the alias. -This name must match the {@code name} attribute of an +This name must match the {@code name} attribute of an <activity> element that precedes the alias in the manifest.

            diff --git a/docs/html/guide/topics/manifest/category-element.jd b/docs/html/guide/topics/manifest/category-element.jd index 0034119fe7b22..d0f0edf6dd8c4 100644 --- a/docs/html/guide/topics/manifest/category-element.jd +++ b/docs/html/guide/topics/manifest/category-element.jd @@ -12,19 +12,19 @@ parent.link=manifest-intro.html
            description:
            Adds a category name to an intent filter. See -Intents and +Intents and Intent Filters for details on intent filters and the role of category specifications within a filter.
            attributes:
            {@code android:name}
            -
            The name of the category. Standard categories are defined in the +
            The name of the category. Standard categories are defined in the {@link android.content.Intent} class as CATEGORY_name -constants. The name assigned here can be derived from those constants -by prefixing "{@code android.intent.category.}" to the +constants. The name assigned here can be derived from those constants +by prefixing "{@code android.intent.category.}" to the name that follows {@code CATEGORY_}. For example, -the string value for {@code CATEGORY_LAUNCHER} is +the string value for {@code CATEGORY_LAUNCHER} is "{@code android.intent.category.LAUNCHER}".

            Note: In order to receive implicit intents, you must include the @@ -39,7 +39,7 @@ your activity.

            Custom categories should use the package name as a prefix, to ensure that they are unique.

            -
            +
            introduced in:
            diff --git a/docs/html/guide/topics/manifest/grant-uri-permission-element.jd b/docs/html/guide/topics/manifest/grant-uri-permission-element.jd index b2d9bb7a104e9..a464e552c47dc 100644 --- a/docs/html/guide/topics/manifest/grant-uri-permission-element.jd +++ b/docs/html/guide/topics/manifest/grant-uri-permission-element.jd @@ -14,24 +14,24 @@ parent.link=manifest-intro.html
            description:
            Specifies which data subsets of the parent content provider permission -can be granted for. Data subsets are indicated by the path part of a +can be granted for. Data subsets are indicated by the path part of a {@code content:} URI. (The authority part of the URI identifies the -content provider.) -Granting permission is a way of enabling clients of the provider that don't -normally have permission to access its data to overcome that restriction on +content provider.) +Granting permission is a way of enabling clients of the provider that don't +normally have permission to access its data to overcome that restriction on a one-time basis. -

            -If a content provider's grantUriPermissions -attribute is "{@code true}", permission can be granted for any the data under -the provider's purview. However, if that attribute is "{@code false}", permission -can be granted only to data subsets that are specified by this element. +

            +If a content provider's grantUriPermissions +attribute is "{@code true}", permission can be granted for any the data under +the provider's purview. However, if that attribute is "{@code false}", permission +can be granted only to data subsets that are specified by this element. A provider can contain any number of {@code } elements. Each one can specify only one path (only one of the three possible attributes).

            -For information on how permission is granted, see the +For information on how permission is granted, see the <intent-filter> element's grantUriPermissions attribute.

            @@ -41,34 +41,34 @@ For information on how permission is granted, see the
            {@code android:path}
            {@code android:pathPrefix}
            {@code android:pathPattern}
            -
            A path identifying the data subset or subsets that permission can be -granted for. The {@code path} attribute specifies a complete path; -permission can be granted only to the particular data subset identified -by that path. -The {@code pathPrefix} attribute specifies the initial part of a path; -permission can be granted to all data subsets with paths that share that -initial part. -The {@code pathPattern} attribute specifies a complete path, but one +
            A path identifying the data subset or subsets that permission can be +granted for. The {@code path} attribute specifies a complete path; +permission can be granted only to the particular data subset identified +by that path. +The {@code pathPrefix} attribute specifies the initial part of a path; +permission can be granted to all data subsets with paths that share that +initial part. +The {@code pathPattern} attribute specifies a complete path, but one that can contain the following wildcards:
            • An asterisk ('{@code *}') matches a sequence of 0 to many occurrences of the immediately preceding character.
            • -
            • A period followed by an asterisk ("{@code .*}") matches any sequence of +

            • A period followed by an asterisk ("{@code .*}") matches any sequence of 0 to many characters.

            -Because '{@code \}' is used as an escape character when the string is read -from XML (before it is parsed as a pattern), you will need to double-escape: -For example, a literal '{@code *}' would be written as "{@code \\*}" and a -literal '{@code \}' would be written as "{@code \\\\}". This is basically +Because '{@code \}' is used as an escape character when the string is read +from XML (before it is parsed as a pattern), you will need to double-escape: +For example, a literal '{@code *}' would be written as "{@code \\*}" and a +literal '{@code \}' would be written as "{@code \\\\}". This is basically the same as what you would need to write if constructing the string in Java code.

            -For more information on these types of patterns, see the descriptions of +For more information on these types of patterns, see the descriptions of {@link android.os.PatternMatcher#PATTERN_LITERAL}, {@link android.os.PatternMatcher#PATTERN_PREFIX}, and {@link android.os.PatternMatcher#PATTERN_SIMPLE_GLOB} in the @@ -81,10 +81,10 @@ For more information on these types of patterns, see the descriptions of

            API Level 1
            see also:
            -
            the +
            the grantUriPermissions -attribute of the -<provider> +attribute of the +<provider> element
            diff --git a/docs/html/guide/topics/manifest/instrumentation-element.jd b/docs/html/guide/topics/manifest/instrumentation-element.jd index 74be559db1374..a476be3b72f1a 100644 --- a/docs/html/guide/topics/manifest/instrumentation-element.jd +++ b/docs/html/guide/topics/manifest/instrumentation-element.jd @@ -23,15 +23,15 @@ object is instantiated before any of the application's components.
            attributes:
            {@code android:functionalTest}
            -
            Whether or not the Instrumentation class should run as a functional test +
            Whether or not the Instrumentation class should run as a functional test — "{@code true}" if it should, and "{@code false}" if not. The default value is "{@code false}".
            {@code android:handleProfiling}
            -
            Whether or not the Instrumentation object will turn profiling on and -off — "{@code true}" if it determines when profiling starts and -stops, and "{@code false}" if profiling continues the entire time it is -running. A value of "{@code true}" enables the object to target profiling +
            Whether or not the Instrumentation object will turn profiling on and +off — "{@code true}" if it determines when profiling starts and +stops, and "{@code false}" if profiling continues the entire time it is +running. A value of "{@code true}" enables the object to target profiling at a specific set of operations. The default value is "{@code false}".
            {@code android:icon}
            @@ -43,11 +43,11 @@ be set as a reference to a drawable resource.
            be set as a raw string or a reference to a string resource.
            {@code android:name}
            -
            The name of the {@link android.app.Instrumentation} subclass. -This should be a fully qualified class name (such as, -"{@code com.example.project.StringInstrumentation}"). However, as a shorthand, -if the first character of the name is a period, it is appended to the package -name specified in the <manifest> element. +
            The name of the {@link android.app.Instrumentation} subclass. +This should be a fully qualified class name (such as, +"{@code com.example.project.StringInstrumentation}"). However, as a shorthand, +if the first character of the name is a period, it is appended to the package +name specified in the <manifest> element.

            There is no default. The name must be specified. diff --git a/docs/html/guide/topics/manifest/intent-filter-element.jd b/docs/html/guide/topics/manifest/intent-filter-element.jd index 14b4e03b64a8f..13956c9ad430d 100644 --- a/docs/html/guide/topics/manifest/intent-filter-element.jd +++ b/docs/html/guide/topics/manifest/intent-filter-element.jd @@ -27,23 +27,23 @@ parent.link=manifest-intro.html

            description:
            Specifies the types of intents that an activity, service, or broadcast receiver can respond to. An intent filter declares the capabilities of its -parent component — what an activity or service can do and what types -of broadcasts a receiver can handle. It opens the component to receiving -intents of the advertised type, while filtering out those that are not +parent component — what an activity or service can do and what types +of broadcasts a receiver can handle. It opens the component to receiving +intents of the advertised type, while filtering out those that are not meaningful for the component.

            -Most of the contents of the filter are described by its -<action>, +Most of the contents of the filter are described by its +<action>, <category>, and <data> subelements.

            -For a more detailed discussion of filters, see the separate -Intents -and Intent Filters document, as well as the -Intents Filters +For a more detailed discussion of filters, see the separate +Intents +and Intent Filters document, as well as the +Intents Filters section in the introduction.

            @@ -51,19 +51,19 @@ section in the introduction.
            {@code android:icon}
            An icon that represents the parent activity, service, or broadcast -receiver when that component is presented to the user as having the +receiver when that component is presented to the user as having the capability described by the filter.

            -This attribute must be set as a reference to a drawable resource -containing the image definition. The default value is the icon set -by the parent component's {@code icon} attribute. If the parent +This attribute must be set as a reference to a drawable resource +containing the image definition. The default value is the icon set +by the parent component's {@code icon} attribute. If the parent does not specify an icon, the default is the icon set by the <application> element.

            -For more on intent filter icons, see +For more on intent filter icons, see Icons and Labels in the introduction.

            @@ -75,44 +75,44 @@ to the user as having the capability described by the filter.

            The label should be set as a reference to a string resource, so that -it can be localized like other strings in the user interface. -However, as a convenience while you're developing the application, +it can be localized like other strings in the user interface. +However, as a convenience while you're developing the application, it can also be set as a raw string.

            -The default value is the label set by the parent component. If the +The default value is the label set by the parent component. If the parent does not specify a label, the default is the label set by the -<application> element's +<application> element's label attribute.

            -For more on intent filter labels, see +For more on intent filter labels, see Icons and Labels in the introduction.

            {@code android:priority}
            The priority that should be given to the parent component with regard -to handling intents of the type described by the filter. This attribute has +to handling intents of the type described by the filter. This attribute has meaning for both activities and broadcast receivers:
              -
            • It provides information about how able an activity is to respond to +
            • It provides information about how able an activity is to respond to an intent that matches the filter, relative to other activities that could -also respond to the intent. When an intent could be handled by multiple +also respond to the intent. When an intent could be handled by multiple activities with different priorities, Android will consider only those with higher priority values as potential targets for the intent.
            • It controls the order in which broadcast receivers are executed to -receive broadcast messages. Those with higher priority -values are called before those with lower values. (The order applies only +receive broadcast messages. Those with higher priority +values are called before those with lower values. (The order applies only to synchronous messages; it's ignored for asynchronous messages.)

            -Use this attribute only if you really need to impose a specific order in +Use this attribute only if you really need to impose a specific order in which the broadcasts are received, or want to force Android to prefer one activity over others.

            diff --git a/docs/html/guide/topics/manifest/meta-data-element.jd b/docs/html/guide/topics/manifest/meta-data-element.jd index d3b41c391195b..2d1bdfe59259c 100644 --- a/docs/html/guide/topics/manifest/meta-data-element.jd +++ b/docs/html/guide/topics/manifest/meta-data-element.jd @@ -19,18 +19,18 @@ parent.link=manifest-intro.html
            description:
            A name-value pair for an item of additional, arbitrary data that can -be supplied to the parent component. A component element can contain any +be supplied to the parent component. A component element can contain any number of {@code } subelements. The values from all of -them are collected in a single {@link android.os.Bundle} object and made -available to the component as the -{@link android.content.pm.PackageItemInfo#metaData +them are collected in a single {@link android.os.Bundle} object and made +available to the component as the +{@link android.content.pm.PackageItemInfo#metaData PackageItemInfo.metaData} field.

            -Ordinary values are specified through the value -attribute. However, to assign a resource ID as the value, use the -resource attribute instead. For example, -the following code assigns whatever value is stored in the {@code @string/kangaroo} +Ordinary values are specified through the value +attribute. However, to assign a resource ID as the value, use the +resource attribute instead. For example, +the following code assigns whatever value is stored in the {@code @string/kangaroo} resource to the "{@code zoo}" name:

            @@ -44,22 +44,22 @@ the numeric ID of the resource, not the value stored in the resource:
            <meta-data android:name="zoo" android:resource="@string/kangaroo" />

            -It is highly recommended that you avoid supplying related data as +It is highly recommended that you avoid supplying related data as multiple separate {@code } entries. Instead, if you -have complex data to associate with a component, store it as a resource and +have complex data to associate with a component, store it as a resource and use the {@code resource} attribute to inform the component of its ID.

            attributes:
            {@code android:name}
            -
            A unique name for the item. To ensure that the name is unique, use a -Java-style naming convention — for example, +
            A unique name for the item. To ensure that the name is unique, use a +Java-style naming convention — for example, "{@code com.example.project.activity.fred}".
            {@code android:resource}
            -
            A reference to a resource. The ID of the resource is the value assigned -to the item. The ID can be retrieved from the meta-data Bundle by the +
            A reference to a resource. The ID of the resource is the value assigned +to the item. The ID can be retrieved from the meta-data Bundle by the {@link android.os.Bundle#getInt Bundle.getInt()} method.
            {@code android:value}
            @@ -70,7 +70,7 @@ to the item. The ID can be retrieved from the meta-data Bundle by the
            - @@ -80,7 +80,7 @@ to the item. The ID can be retrieved from the meta-data Bundle by the - diff --git a/docs/html/guide/topics/manifest/path-permission-element.jd b/docs/html/guide/topics/manifest/path-permission-element.jd index cdaf82b00f292..4774707331514 100644 --- a/docs/html/guide/topics/manifest/path-permission-element.jd +++ b/docs/html/guide/topics/manifest/path-permission-element.jd @@ -33,9 +33,9 @@ specified multiple times to supply multiple paths.
            {@code android:path}
            -
            A complete URI path for a subset of content provider data. -Permission can be granted only to the particular data identified by this path. -When used to provide search suggestion content, it must be appended +
            A complete URI path for a subset of content provider data. +Permission can be granted only to the particular data identified by this path. +When used to provide search suggestion content, it must be appended with "/search_suggest_query".
            @@ -47,24 +47,24 @@ Permission can be granted to all data subsets with paths that share this initial
            {@code android:pathPattern}
            A complete URI path for a subset of content provider data, but one that can use the following wildcards: - -
              + +
              • An asterisk ('*'). This matches a sequence of 0 to many occurrences of -the immediately preceding character.
              • - -
              • A period followed by an asterisk (".*"). This matches any sequence of -0 or more characters.
              • -
              - -

              -Because '\' is used as an escape character when the string is read +the immediately preceding character. + +

            • A period followed by an asterisk (".*"). This matches any sequence of +0 or more characters.
            • +
            + +

            +Because '\' is used as an escape character when the string is read from XML (before it is parsed as a pattern), you will need to double-escape. -For example, a literal '*' would be written as "\\*" and a -literal '\' would be written as "\\". This is basically +For example, a literal '*' would be written as "\\*" and a +literal '\' would be written as "\\". This is basically the same as what you would need to write if constructing the string in Java code. -

            -

            -For more information on these types of patterns, see the descriptions of +

            +

            +For more information on these types of patterns, see the descriptions of PATTERN_LITERAL, PATTERN_PREFIX, and PATTERN_SIMPLE_GLOB in the @@ -74,20 +74,20 @@ For more information on these types of patterns, see the descriptions of

            {@code android:permission}
            The name of a permission that clients must have in order to read or write the -content provider's data. This attribute is a convenient way of setting a -single permission for both reading and writing. However, the -readPermission and +content provider's data. This attribute is a convenient way of setting a +single permission for both reading and writing. However, the +readPermission and writePermission attributes take precedence over this one. -
            +
            {@code android:readPermission}
            A permission that clients must have in order to query the content provider. -
            +
            {@code android:writePermission}
            A permission that clients must have in order to make changes to the data controlled by the content provider. -
            + diff --git a/docs/html/guide/topics/manifest/permission-group-element.jd b/docs/html/guide/topics/manifest/permission-group-element.jd index 3221d4b68c364..85452b534fcfc 100644 --- a/docs/html/guide/topics/manifest/permission-group-element.jd +++ b/docs/html/guide/topics/manifest/permission-group-element.jd @@ -20,17 +20,17 @@ permission join the group through the {@code permissionGroup} attribute of the presented together in the user interface.

            -Note that this element does not declare a permission itself, only a category in -which permissions can be placed. See the -<permission> element for element for information +Note that this element does not declare a permission itself, only a category in +which permissions can be placed. See the +<permission> element for element for information on declaring permissions and assigning them to groups.

            attributes:
            {@code android:description}
            -
            User-readable text that describes the group. The text should be -longer and more explanatory than the label. This attribute must be +
            User-readable text that describes the group. The text should be +longer and more explanatory than the label. This attribute must be set as a reference to a string resource. Unlike the {@code label} attribute, it cannot be a raw string.
            @@ -39,10 +39,10 @@ attribute, it cannot be a raw string.
            as a reference to a drawable resource containing the image definition.
            {@code android:label}
            -
            A user-readable name for the group. As a convenience, the label can -be directly set as a raw string while you're developing the application. -However, when the application is ready to be published, it should be set -as a reference to a string resource, so that it can be localized like other +
            A user-readable name for the group. As a convenience, the label can +be directly set as a raw string while you're developing the application. +However, when the application is ready to be published, it should be set +as a reference to a string resource, so that it can be localized like other strings in the user interface.
            {@code android:name}
            diff --git a/docs/html/guide/topics/manifest/permission-tree-element.jd b/docs/html/guide/topics/manifest/permission-tree-element.jd index 21d7352331f3b..cbfd72cd8465a 100644 --- a/docs/html/guide/topics/manifest/permission-tree-element.jd +++ b/docs/html/guide/topics/manifest/permission-tree-element.jd @@ -14,7 +14,7 @@ parent.link=manifest-intro.html
            description:
            Declares the base name for a tree of permissions. The application takes -ownership of all names within the tree. It can dynamically add new permissions +ownership of all names within the tree. It can dynamically add new permissions to the tree by calling {@link android.content.pm.PackageManager#addPermission PackageManager.addPermission()}. Names within the tree are separated by periods ('{@code .}'). For example, if the base name is {@code com.example.project.taxes}, permissions like the following might be @@ -25,30 +25,30 @@ added:
            {@code com.example.project.taxes.deductions.EXAGGERATE}

            -Note that this element does not declare a permission itself, only a -namespace in which further permissions can be placed. See the -<permission> +Note that this element does not declare a permission itself, only a +namespace in which further permissions can be placed. See the +<permission> element for information on declaring permissions.

            attributes:
            {@code android:icon}
            -
            An icon representing all the permissions in the tree. This attribute -must be set as a reference to a drawable resource containing the image +
            An icon representing all the permissions in the tree. This attribute +must be set as a reference to a drawable resource containing the image definition.
            {@code android:label}
            -
            A user-readable name for the group. As a convenience, the label can -be directly set as a raw string for quick and dirty programming. However, -when the application is ready to be published, it should be set as a -reference to a string resource, so that it can be localized like other +
            A user-readable name for the group. As a convenience, the label can +be directly set as a raw string for quick and dirty programming. However, +when the application is ready to be published, it should be set as a +reference to a string resource, so that it can be localized like other strings in the user interface.
            {@code android:name}
            -
            The name that's at the base of the permission tree. It serves as -a prefix to all permission names in the tree. Java-style scoping should -be used to ensure that the name is unique. The name must have more than -two period-separated segments in its path — for example, +
            The name that's at the base of the permission tree. It serves as +a prefix to all permission names in the tree. Java-style scoping should +be used to ensure that the name is unique. The name must have more than +two period-separated segments in its path — for example, {@code com.example.base} is OK, but {@code com.example} is not.
            diff --git a/docs/html/guide/topics/manifest/provider-element.jd b/docs/html/guide/topics/manifest/provider-element.jd index 4b5c0c35bc2cd..1947849e56f83 100644 --- a/docs/html/guide/topics/manifest/provider-element.jd +++ b/docs/html/guide/topics/manifest/provider-element.jd @@ -37,41 +37,41 @@ parent.link=manifest-intro.html
            description:
            - Declares a content provider component. A content provider is a subclass of - {@link android.content.ContentProvider} that supplies structured access to data managed by the - application. All content providers in your application must be defined in a + Declares a content provider component. A content provider is a subclass of + {@link android.content.ContentProvider} that supplies structured access to data managed by the + application. All content providers in your application must be defined in a {@code } element in the manifest file; otherwise, the system is unaware of them and doesn't run them.

            You only declare content providers that are part of your application. Content providers in other applications that you use in your application should not be declared. -

            +

            The Android system stores references to content providers according to an authority - string, part of the provider's content URI. For example, suppose you want to + string, part of the provider's content URI. For example, suppose you want to access a content provider that stores information about health care professionals. To do - this, you call the method + this, you call the method {@link android.content.ContentResolver#query ContentResolver.query()}, which among other arguments takes a URI that identifies the provider: -

            +

             content://com.example.project.healthcareprovider/nurses/rn
             

            The content: scheme identifies the URI as a content URI pointing to - an Android content provider. The authority + an Android content provider. The authority com.example.project.healthcareprovider identifies the provider itself; the - Android system looks up the authority in its list of known providers and their authorities. - The substring nurses/rn is a path, which the content provider can use + Android system looks up the authority in its list of known providers and their authorities. + The substring nurses/rn is a path, which the content provider can use to identify subsets of the provider data.

            - Notice that when you define your provider in the <provider> element, you + Notice that when you define your provider in the <provider> element, you don't include the scheme or the path in the android:name argument, only the - authority. + authority.

            - For information on using and developing content providers, see the API Guide, + For information on using and developing content providers, see the API Guide, Content Providers.

            @@ -82,8 +82,8 @@ content://com.example.project.healthcareprovider/nurses/rn
            {@code android:authorities}
            A list of one or more URI authorities that identify data offered by the content provider. - Multiple authorities are listed by separating their names with a semicolon. - To avoid conflicts, authority names should use a Java-style naming convention + Multiple authorities are listed by separating their names with a semicolon. + To avoid conflicts, authority names should use a Java-style naming convention (such as {@code com.example.provider.cartoonprovider}). Typically, it's the name of the {@link android.content.ContentProvider} subclass that implements the provider

            @@ -92,92 +92,92 @@ content://com.example.project.healthcareprovider/nurses/rn

            {@code android:enabled}
            -
            Whether or not the content provider can be instantiated by the system — - "{@code true}" if it can be, and "{@code false}" if not. The default value +
            Whether or not the content provider can be instantiated by the system — + "{@code true}" if it can be, and "{@code false}" if not. The default value is "{@code true}".

            -The <application> element has its own -enabled attribute that applies to all -application components, including content providers. The +The <application> element has its own +enabled attribute that applies to all +application components, including content providers. The <application> and {@code } attributes must both be "{@code true}" (as they both -are by default) for the content provider to be enabled. If either is +are by default) for the content provider to be enabled. If either is "{@code false}", the provider is disabled; it cannot be instantiated.

            {@code android:exported}
            Whether the content provider is available for other applications to use: -
              +
              • true: The provider is available to other applications. Any application can use the provider's content URI to access it, subject to the permissions specified for the provider.
              • - false: The provider is not available to other applications. Set + false: The provider is not available to other applications. Set android:exported="false" to limit access to the provider to your applications. Only applications that have the same user ID (UID) as the provider will have access to it.

              - The default value is "true" for applications that set either + The default value is "true" for applications that set either android:minSdkVersion - or -android:targetSdkVersion to + or +android:targetSdkVersion to "16" or lower. For applications that - set either of these attributes to "17" or higher, the default is + set either of these attributes to "17" or higher, the default is "false".

              You can set android:exported="false" and still limit access to your - provider by setting permissions with the + provider by setting permissions with the permission attribute.

              -
            +
            {@code android:grantUriPermissions}
            -
            Whether or not those who ordinarily would not have permission to +
            Whether or not those who ordinarily would not have permission to access the content provider's data can be granted permission to do so, temporarily overcoming the restriction imposed by the readPermission, -writePermission, and -permission attributes -— -"{@code true}" if permission can be granted, and "{@code false}" if not. -If "{@code true}", permission can be granted to any of the content -provider's data. If "{@code false}", permission can be granted only -to the data subsets listed in -<grant-uri-permission> subelements, +writePermission, and +permission attributes +— +"{@code true}" if permission can be granted, and "{@code false}" if not. +If "{@code true}", permission can be granted to any of the content +provider's data. If "{@code false}", permission can be granted only +to the data subsets listed in +<grant-uri-permission> subelements, if any. The default value is "{@code false}".

            -Granting permission is a way of giving an application component one-time -access to data protected by a permission. For example, when an e-mail -message contains an attachment, the mail application may call upon the -appropriate viewer to open it, even though the viewer doesn't have general -permission to look at all the content provider's data. +Granting permission is a way of giving an application component one-time +access to data protected by a permission. For example, when an e-mail +message contains an attachment, the mail application may call upon the +appropriate viewer to open it, even though the viewer doesn't have general +permission to look at all the content provider's data.

            -

            -In such cases, permission is granted by -{@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} -and {@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} -flags in the Intent object that activates the component. For example, the -mail application might put {@code FLAG_GRANT_READ_URI_PERMISSION} in the -Intent passed to {@code Context.startActivity()}. The permission is specific -to the URI in the Intent. +

            +In such cases, permission is granted by +{@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} +and {@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} +flags in the Intent object that activates the component. For example, the +mail application might put {@code FLAG_GRANT_READ_URI_PERMISSION} in the +Intent passed to {@code Context.startActivity()}. The permission is specific +to the URI in the Intent.

            If you enable this feature, either by setting this attribute to "{@code true}" -or by defining <grant-uri-permission> -subelements, you must call -{@link android.content.Context#revokeUriPermission -Context.revokeUriPermission()} when a covered URI is deleted from +or by defining <grant-uri-permission> +subelements, you must call +{@link android.content.Context#revokeUriPermission +Context.revokeUriPermission()} when a covered URI is deleted from the provider.

            @@ -187,52 +187,52 @@ element.

            {@code android:icon}
            -
            An icon representing the content provider. -This attribute must be set as a reference to a drawable resource containing -the image definition. If it is not set, the icon specified for the application -as a whole is used instead (see the <application> +
            An icon representing the content provider. +This attribute must be set as a reference to a drawable resource containing +the image definition. If it is not set, the icon specified for the application +as a whole is used instead (see the <application> element's icon attribute).
            {@code android:initOrder}
            -
            The order in which the content provider should be instantiated, -relative to other content providers hosted by the same process. -When there are dependencies among content providers, setting this -attribute for each of them ensures that they are created in the order -required by those dependencies. The value is a simple integer, +
            The order in which the content provider should be instantiated, +relative to other content providers hosted by the same process. +When there are dependencies among content providers, setting this +attribute for each of them ensures that they are created in the order +required by those dependencies. The value is a simple integer, with higher numbers being initialized first.
            {@code android:label}
            -
            A user-readable label for the content provided. -If this attribute is not set, the label set for the application as a whole is -used instead (see the <application> element's +
            A user-readable label for the content provided. +If this attribute is not set, the label set for the application as a whole is +used instead (see the <application> element's label attribute).

            The label should be set as a reference to a string resource, so that -it can be localized like other strings in the user interface. -However, as a convenience while you're developing the application, +it can be localized like other strings in the user interface. +However, as a convenience while you're developing the application, it can also be set as a raw string.

            {@code android:multiprocess}
            -
            Whether or not an instance of the content provider can be created in +
            Whether or not an instance of the content provider can be created in every client process — "{@code true}" if instances can run in multiple processes, and "{@code false}" if not. The default value is "{@code false}".

            -Normally, a content provider is instantiated in the process of the -application that defined it. However, if this flag is set to "{@code true}", -the system can create an instance in every process where there's a client -that wants to interact with it, thus avoiding the overhead of interprocess +Normally, a content provider is instantiated in the process of the +application that defined it. However, if this flag is set to "{@code true}", +the system can create an instance in every process where there's a client +that wants to interact with it, thus avoiding the overhead of interprocess communication.

            {@code android:name}
            -
            The name of the class that implements the content provider, a subclass of -{@link android.content.ContentProvider}. This should be a fully qualified -class name (such as, "{@code com.example.project.TransportationProvider}"). -However, as a shorthand, if the first character of the name is a period, -it is appended to the package name specified in the +
            The name of the class that implements the content provider, a subclass of +{@link android.content.ContentProvider}. This should be a fully qualified +class name (such as, "{@code com.example.project.TransportationProvider}"). +However, as a shorthand, if the first character of the name is a period, +it is appended to the package name specified in the <manifest> element.

            @@ -242,58 +242,58 @@ There is no default. The name must be specified.

            {@code android:permission}
            The name of a permission that clients must have to read or write the -content provider's data. This attribute is a convenient way of setting a -single permission for both reading and writing. However, the -readPermission and +content provider's data. This attribute is a convenient way of setting a +single permission for both reading and writing. However, the +readPermission and writePermission attributes take precedence -over this one. If the readPermission +over this one. If the readPermission attribute is also set, it controls access for querying the content provider. And if the writePermission attribute is set, it controls access for modifying the provider's data.

            -For more information on permissions, see the -Permissions -section in the introduction and a separate document, +For more information on permissions, see the +Permissions +section in the introduction and a separate document, Security and Permissions.

            {@code android:process}
            -
            The name of the process in which the content provider should run. Normally, -all components of an application run in the default process created for the -application. It has the same name as the application package. The -<application> element's -process -attribute can set a different +
            The name of the process in which the content provider should run. Normally, +all components of an application run in the default process created for the +application. It has the same name as the application package. The +<application> element's +process +attribute can set a different default for all components. But each component can override the default -with its own {@code process} attribute, allowing you to spread your +with its own {@code process} attribute, allowing you to spread your application across multiple processes.

            -If the name assigned to this attribute begins with a colon (':'), a new -process, private to the application, is created when it's needed and +If the name assigned to this attribute begins with a colon (':'), a new +process, private to the application, is created when it's needed and the activity runs in that process. -If the process name begins with a lowercase character, the activity will run +If the process name begins with a lowercase character, the activity will run in a global process of that name, provided that it has permission to do so. -This allows components in different applications to share a process, reducing +This allows components in different applications to share a process, reducing resource usage.

            {@code android:readPermission}
            -
            A permission that clients must have to query the content provider. -See also the permission and +
            A permission that clients must have to query the content provider. +See also the permission and writePermission attributes.
            {@code android:syncable}
            -
            Whether or not the data under the content provider's control -is to be synchronized with data on a server — "{@code true}" +
            Whether or not the data under the content provider's control +is to be synchronized with data on a server — "{@code true}" if it is to be synchronized, and "{@code false}" if not.
            {@code android:writePermission}
            -
            A permission that clients must have to make changes to the data -controlled by the content provider. -See also the permission and +
            A permission that clients must have to make changes to the data +controlled by the content provider. +See also the permission and readPermission attributes.
            diff --git a/docs/html/guide/topics/manifest/receiver-element.jd b/docs/html/guide/topics/manifest/receiver-element.jd index 081a191c38e19..800ee8a6e4c75 100644 --- a/docs/html/guide/topics/manifest/receiver-element.jd +++ b/docs/html/guide/topics/manifest/receiver-element.jd @@ -24,14 +24,14 @@ parent.link=manifest-intro.html
            description:
            Declares a broadcast receiver (a {@link android.content.BroadcastReceiver} -subclass) as one of the application's components. Broadcast receivers enable -applications to receive intents that are broadcast by the system or by other +subclass) as one of the application's components. Broadcast receivers enable +applications to receive intents that are broadcast by the system or by other applications, even when other components of the application are not running.

            There are two ways to make a broadcast receiver known to the system: One is declare it in the manifest file with this element. The other is to create -the receiver dynamically in code and register it with the {@link +the receiver dynamically in code and register it with the {@link android.content.Context#registerReceiver Context.registerReceiver()} method. See the {@link android.content.BroadcastReceiver} class description for more on dynamically created receivers. @@ -40,14 +40,14 @@ for more on dynamically created receivers.

            attributes:
            {@code android:enabled}
            -
            Whether or not the broadcast receiver can be instantiated by the system — -"{@code true}" if it can be, and "{@code false}" if not. The default value +
            Whether or not the broadcast receiver can be instantiated by the system — +"{@code true}" if it can be, and "{@code false}" if not. The default value is "{@code true}".

            -The <application> element has its own -enabled attribute that applies to all -application components, including broadcast receivers. The +The <application> element has its own +enabled attribute that applies to all +application components, including broadcast receivers. The <application> and {@code } attributes must both be "{@code true}" for the broadcast receiver to be enabled. If either is "{@code false}", it is @@ -55,72 +55,72 @@ disabled; it cannot be instantiated.

            {@code android:exported}
            -
            Whether or not the broadcast receiver can receive messages from sources -outside its application — "{@code true}" if it can, and "{@code false}" -if not. If "{@code false}", the only messages the broadcast receiver can -receive are those sent by components of the same application or applications -with the same user ID. +
            Whether or not the broadcast receiver can receive messages from sources +outside its application — "{@code true}" if it can, and "{@code false}" +if not. If "{@code false}", the only messages the broadcast receiver can +receive are those sent by components of the same application or applications +with the same user ID.

            -The default value depends on whether the broadcast receiver contains intent filters. +The default value depends on whether the broadcast receiver contains intent filters. The absence of any filters means that it can be invoked only by Intent objects that -specify its exact class name. This implies that the receiver is intended only for -application-internal use (since others would not normally know the class name). +specify its exact class name. This implies that the receiver is intended only for +application-internal use (since others would not normally know the class name). So in this case, the default value is "{@code false}". -On the other hand, the presence of at least one filter implies that the broadcast -receiver is intended to receive intents broadcast by the system or other applications, +On the other hand, the presence of at least one filter implies that the broadcast +receiver is intended to receive intents broadcast by the system or other applications, so the default value is "{@code true}".

            -This attribute is not the only way to limit a broadcast receiver's external exposure. -You can also use a permission to limit the external entities that can send it messages +This attribute is not the only way to limit a broadcast receiver's external exposure. +You can also use a permission to limit the external entities that can send it messages (see the permission attribute).

            {@code android:icon}
            -
            An icon representing the broadcast receiver. This attribute must be set -as a reference to a drawable resource containing the image definition. -If it is not set, the icon specified for the application as a whole is used -instead (see the <application> +
            An icon representing the broadcast receiver. This attribute must be set +as a reference to a drawable resource containing the image definition. +If it is not set, the icon specified for the application as a whole is used +instead (see the <application> element's icon attribute).

            -The broadcast receiver's icon — whether set here or by the -<application> element — is also the -default icon for all the receiver's intent filters (see the -<intent-filter> element's -icon attribute). +The broadcast receiver's icon — whether set here or by the +<application> element — is also the +default icon for all the receiver's intent filters (see the +<intent-filter> element's +icon attribute).

            {@code android:label}
            -
            A user-readable label for the broadcast receiver. If this attribute is not -set, the label set for the application as a whole is -used instead (see the <application> element's +
            A user-readable label for the broadcast receiver. If this attribute is not +set, the label set for the application as a whole is +used instead (see the <application> element's label attribute).

            -The broadcast receiver's label — whether set here or by the -<application> element — is also the -default label for all the receiver's intent filters (see the -<intent-filter> element's -label attribute). +The broadcast receiver's label — whether set here or by the +<application> element — is also the +default label for all the receiver's intent filters (see the +<intent-filter> element's +label attribute).

            The label should be set as a reference to a string resource, so that -it can be localized like other strings in the user interface. -However, as a convenience while you're developing the application, +it can be localized like other strings in the user interface. +However, as a convenience while you're developing the application, it can also be set as a raw string.

            {@code android:name}
            -
            The name of the class that implements the broadcast receiver, a subclass of -{@link android.content.BroadcastReceiver}. This should be a fully qualified -class name (such as, "{@code com.example.project.ReportReceiver}"). However, -as a shorthand, if the first character of the name is a period (for example, -"{@code . ReportReceiver}"), it is appended to the package name specified in -the <manifest> element. +
            The name of the class that implements the broadcast receiver, a subclass of +{@link android.content.BroadcastReceiver}. This should be a fully qualified +class name (such as, "{@code com.example.project.ReportReceiver}"). However, +as a shorthand, if the first character of the name is a period (for example, +"{@code . ReportReceiver}"), it is appended to the package name specified in +the <manifest> element.

            Once you publish your application, you should not @@ -132,38 +132,38 @@ There is no default. The name must be specified.

            {@code android:permission}
            -
            The name of a permission that broadcasters must have to send a +
            The name of a permission that broadcasters must have to send a message to the broadcast receiver. -If this attribute is not set, the permission set by the +If this attribute is not set, the permission set by the <application> element's -permission attribute applies -to the broadcast receiver. If neither attribute is set, the receiver +permission attribute applies +to the broadcast receiver. If neither attribute is set, the receiver is not protected by a permission.

            -For more information on permissions, see the -Permissions -section in the introduction and a separate document, +For more information on permissions, see the +Permissions +section in the introduction and a separate document, Security and Permissions.

            {@code android:process}
            -
            The name of the process in which the broadcast receiver should run. -Normally, all components of an application run in the default process created -for the application. It has the same name as the application package. The -<application> element's -process attribute can set a different +
            The name of the process in which the broadcast receiver should run. +Normally, all components of an application run in the default process created +for the application. It has the same name as the application package. The +<application> element's +process attribute can set a different default for all components. But each component can override the default -with its own {@code process} attribute, allowing you to spread your +with its own {@code process} attribute, allowing you to spread your application across multiple processes.

            -If the name assigned to this attribute begins with a colon (':'), a new -process, private to the application, is created when it's needed and +If the name assigned to this attribute begins with a colon (':'), a new +process, private to the application, is created when it's needed and the broadcast receiver runs in that process. -If the process name begins with a lowercase character, the receiver will run +If the process name begins with a lowercase character, the receiver will run in a global process of that name, provided that it has permission to do so. -This allows components in different applications to share a process, reducing +This allows components in different applications to share a process, reducing resource usage.

            diff --git a/docs/html/guide/topics/manifest/service-element.jd b/docs/html/guide/topics/manifest/service-element.jd index fca85f5793c87..9197a7f034357 100644 --- a/docs/html/guide/topics/manifest/service-element.jd +++ b/docs/html/guide/topics/manifest/service-element.jd @@ -25,108 +25,108 @@ parent.link=manifest-intro.html
            description:
            Declares a service (a {@link android.app.Service} subclass) as one -of the application's components. Unlike activities, services lack a -visual user interface. They're used to implement long-running background -operations or a rich communications API that can be called by other +of the application's components. Unlike activities, services lack a +visual user interface. They're used to implement long-running background +operations or a rich communications API that can be called by other applications.

            All services must be represented by {@code } elements in -the manifest file. Any that are not declared there will not be seen +the manifest file. Any that are not declared there will not be seen by the system and will never be run.

            attributes:
            {@code android:enabled}
            -
            Whether or not the service can be instantiated by the system — -"{@code true}" if it can be, and "{@code false}" if not. The default value +
            Whether or not the service can be instantiated by the system — +"{@code true}" if it can be, and "{@code false}" if not. The default value is "{@code true}".

            -The <application> element has its own -enabled attribute that applies to all -application components, including services. The +The <application> element has its own +enabled attribute that applies to all +application components, including services. The <application> and {@code } attributes must both be "{@code true}" (as they both -are by default) for the service to be enabled. If either is +are by default) for the service to be enabled. If either is "{@code false}", the service is disabled; it cannot be instantiated.

            {@code android:exported}
            -
            Whether or not components of other applications can invoke -the service or interact with it — "{@code true}" if they can, and -"{@code false}" if not. When the value is "{@code false}", only -components of the same application or applications +
            Whether or not components of other applications can invoke +the service or interact with it — "{@code true}" if they can, and +"{@code false}" if not. When the value is "{@code false}", only +components of the same application or applications with the same user ID can start the service or bind to it.

            -The default value depends on whether the service contains intent filters. The -absence of any filters means that it can be invoked only by specifying -its exact class name. This implies that the service is intended only for -application-internal use (since others would not know the class name). So in +The default value depends on whether the service contains intent filters. The +absence of any filters means that it can be invoked only by specifying +its exact class name. This implies that the service is intended only for +application-internal use (since others would not know the class name). So in this case, the default value is "{@code false}". -On the other hand, the presence of at least one filter implies that the service +On the other hand, the presence of at least one filter implies that the service is intended for external use, so the default value is "{@code true}".

            This attribute is not the only way to limit the exposure of a service to other -applications. You can also use a permission to limit the external entities that -can interact with the service (see the permission +applications. You can also use a permission to limit the external entities that +can interact with the service (see the permission attribute).

            {@code android:icon}
            -
            An icon representing the service. This attribute must be set as a -reference to a drawable resource containing the image definition. -If it is not set, the icon specified for the application -as a whole is used instead (see the <application> +
            An icon representing the service. This attribute must be set as a +reference to a drawable resource containing the image definition. +If it is not set, the icon specified for the application +as a whole is used instead (see the <application> element's icon attribute).

            -The service's icon — whether set here or by the -<application> element — is also the -default icon for all the service's intent filters (see the -<intent-filter> element's +The service's icon — whether set here or by the +<application> element — is also the +default icon for all the service's intent filters (see the +<intent-filter> element's icon attribute). -

            +

            {@code android:isolatedProcess}
            If set to true, this service will run under a special process that is isolated from the rest of the system and has no permissions of its own. - The only communication with it is through the Service API + The only communication with it is through the Service API (binding and starting).
            {@code android:label}
            -
            A name for the service that can be displayed to users. -If this attribute is not set, the label set for the application as a whole is -used instead (see the <application> element's +
            A name for the service that can be displayed to users. +If this attribute is not set, the label set for the application as a whole is +used instead (see the <application> element's label attribute).

            -The service's label — whether set here or by the -<application> element — is also the -default label for all the service's intent filters (see the -<intent-filter> element's -label attribute). +The service's label — whether set here or by the +<application> element — is also the +default label for all the service's intent filters (see the +<intent-filter> element's +label attribute).

            The label should be set as a reference to a string resource, so that -it can be localized like other strings in the user interface. -However, as a convenience while you're developing the application, +it can be localized like other strings in the user interface. +However, as a convenience while you're developing the application, it can also be set as a raw string.

            {@code android:name}
            -
            The name of the {@link android.app.Service} subclass that implements -the service. This should be a fully qualified class name (such as, -"{@code com.example.project.RoomService}"). However, as a shorthand, if +
            The name of the {@link android.app.Service} subclass that implements +the service. This should be a fully qualified class name (such as, +"{@code com.example.project.RoomService}"). However, as a shorthand, if the first character of the name is a period (for example, "{@code .RoomService}"), -it is appended to the package name specified in the -<manifest> element. +it is appended to the package name specified in the +<manifest> element.

            Once you publish your application, you should not @@ -138,8 +138,8 @@ There is no default. The name must be specified.

            {@code android:permission}
            -
            The name of a permission that an entity must have in order to -launch the service or bind to it. If a caller of +
            The name of a permission that an entity must have in order to +launch the service or bind to it. If a caller of {@link android.content.Context#startService startService()}, {@link android.content.Context#bindService bindService()}, or {@link android.content.Context#stopService stopService()}, @@ -147,38 +147,38 @@ has not been granted this permission, the method will not work and the Intent object will not be delivered to the service.

            -If this attribute is not set, the permission set by the +If this attribute is not set, the permission set by the <application> element's -permission +permission attribute applies to the service. If neither attribute is set, the service is not protected by a permission.

            -For more information on permissions, see the -Permissions -section in the introduction and a separate document, +For more information on permissions, see the +Permissions +section in the introduction and a separate document, Security and Permissions.

            {@code android:process}
            -
            The name of the process where the service is to run. Normally, -all components of an application run in the default process created for the -application. It has the same name as the application package. The -<application> element's -process -attribute can set a different +
            The name of the process where the service is to run. Normally, +all components of an application run in the default process created for the +application. It has the same name as the application package. The +<application> element's +process +attribute can set a different default for all components. But component can override the default -with its own {@code process} attribute, allowing you to spread your +with its own {@code process} attribute, allowing you to spread your application across multiple processes.

            -If the name assigned to this attribute begins with a colon (':'), a new -process, private to the application, is created when it's needed and +If the name assigned to this attribute begins with a colon (':'), a new +process, private to the application, is created when it's needed and the service runs in that process. -If the process name begins with a lowercase character, the service will run +If the process name begins with a lowercase character, the service will run in a global process of that name, provided that it has permission to do so. -This allows components in different applications to share a process, reducing +This allows components in different applications to share a process, reducing resource usage.

            diff --git a/docs/html/guide/topics/manifest/supports-gl-texture-element.jd b/docs/html/guide/topics/manifest/supports-gl-texture-element.jd index ab751c217f05c..a72fc818b74b8 100644 --- a/docs/html/guide/topics/manifest/supports-gl-texture-element.jd +++ b/docs/html/guide/topics/manifest/supports-gl-texture-element.jd @@ -3,16 +3,16 @@ parent.title=The AndroidManifest.xml File parent.link=manifest-intro.html @jd:body -
            - - - + - + - + - + - +
            Listener interface Type Bundle method
            String value, using double backslashes ({@code \\}) to escape characters + String value, using double backslashes ({@code \\}) to escape characters — such as "{@code \\n}" and "{@code \\uxxxxx}" for a Unicode character. {@link android.os.Bundle#getString(String) getString()}
            Boolean value, either "{@code true}" or "{@code false}" {@link android.os.Bundle#getBoolean(String) getBoolean()}
            Color value, in the form "{@code #rgb}", "{@code #argb}", + Color value, in the form "{@code #rgb}", "{@code #argb}", "{@code #rrggbb}", or "{@code #aarrggbb}" {@link android.os.Bundle#getInt(String) getInt()}

            {@link android.provider.CalendarContract.Calendars}

            This table holds + + This table holds the calendar-specific information. Each row in this table contains the details for a single calendar, such as the name, color, sync information, and so on.
            {@link android.provider.CalendarContract.Events}This table holds the event-specific information. Each row in this table has the information for a single event—for example, event title, location, start time, end time, and so on. The event can occur one-time or can recur multiple times. Attendees, -reminders, and extended properties are stored in separate tables. -They each have an {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} +reminders, and extended properties are stored in separate tables. +They each have an {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} that references the {@link android.provider.BaseColumns#_ID} in the Events table.
            {@link android.provider.CalendarContract.Instances}This table holds the start and end time for each occurrence of an event. Each row in this table represents a single event occurrence. For one-time events there is a 1:1 mapping @@ -141,7 +141,7 @@ of instances to events. For recurring events, multiple rows are automatically
            {@link android.provider.CalendarContract.Attendees}This table holds the event attendee (guest) information. Each row represents a single guest of an event. It specifies the type of guest and the guest's attendance response @@ -149,17 +149,17 @@ for the event.
            {@link android.provider.CalendarContract.Reminders}This table holds the alert/notification data. Each row represents a single alert for an event. An event can have multiple reminders. The maximum number of reminders per event is -specified in -{@link android.provider.CalendarContract.CalendarColumns#MAX_REMINDERS}, +specified in +{@link android.provider.CalendarContract.CalendarColumns#MAX_REMINDERS}, which is set by the sync adapter that owns the given calendar. Reminders are specified in minutes before the event and have a method that determines how the user will be alerted.

            The Calendar Provider API is designed to be flexible and powerful. At the @@ -178,9 +178,9 @@ Intents.

          7. Sync adapters. A sync adapter synchronizes the calendar data -on a user's device with another server or data source. In the +on a user's device with another server or data source. In the {@link android.provider.CalendarContract.Calendars} and -{@link android.provider.CalendarContract.Events} tables, +{@link android.provider.CalendarContract.Events} tables, there are columns that are reserved for the sync adapters to use. The provider and applications should not modify them. In fact, they are not visible unless they are accessed as a sync adapter. For more information about @@ -209,9 +209,9 @@ to delete, insert or update calendar data:

            Calendars Table

            -

            The {@link android.provider.CalendarContract.Calendars} table contains details +

            The {@link android.provider.CalendarContract.Calendars} table contains details for individual calendars. The following -Calendars columns are writable by both an application and a sync adapter. +Calendars columns are writable by both an application and a sync adapter. For a full list of supported fields, see the {@link android.provider.CalendarContract.Calendars} reference.

            @@ -229,7 +229,7 @@ For a full list of supported fields, see the - + - +

            Here is an example that shows how to get the calendars that are owned by a particular user. For simplicity's sake, in this example the query operation is shown in the user interface thread ("main thread"). In practice, this should be done in an asynchronous -thread instead of on the main thread. For more discussion, see -Loaders. If you are not just +thread instead of on the main thread. For more discussion, see +Loaders. If you are not just reading data but modifying it, see {@link android.content.AsyncQueryHandler}.

            @@ -268,18 +268,18 @@ public static final String[] EVENT_PROJECTION = new String[] { Calendars.CALENDAR_DISPLAY_NAME, // 2 Calendars.OWNER_ACCOUNT // 3 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1; private static final int PROJECTION_DISPLAY_NAME_INDEX = 2; private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3; - + +synced.

            In the next part of the example, you construct your query. The selection @@ -301,59 +301,59 @@ calendars that have the ACCOUNT_NAME has viewed, not just calendars the user owns, omit the OWNER_ACCOUNT. The query returns a {@link android.database.Cursor} object that you can use to traverse the result set returned by the database -query. For more discussion of using queries in content providers, +query. For more discussion of using queries in content providers, see Content Providers.

            // Run query
             Cursor cur = null;
             ContentResolver cr = getContentResolver();
            -Uri uri = Calendars.CONTENT_URI;   
            -String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" 
            +Uri uri = Calendars.CONTENT_URI;
            +String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND ("
                                     + Calendars.ACCOUNT_TYPE + " = ?) AND ("
                                     + Calendars.OWNER_ACCOUNT + " = ?))";
             String[] selectionArgs = new String[] {"sampleuser@gmail.com", "com.google",
            -        "sampleuser@gmail.com"}; 
            -// Submit the query and get a Cursor object back. 
            +        "sampleuser@gmail.com"};
            +// Submit the query and get a Cursor object back.
             cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);

            This next section uses the cursor to step through the result set. It uses the constants that were set up at the beginning of the example to return the values for each field.

            - +
            // Use the cursor to step through the returned records
             while (cur.moveToNext()) {
                 long calID = 0;
                 String displayName = null;
                 String accountName = null;
                 String ownerName = null;
            -      
            +
                 // Get the field values
                 calID = cur.getLong(PROJECTION_ID_INDEX);
                 displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
                 accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
                 ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
            -              
            +
                 // Do something with the values...
             
                ...
             }
             
            - +

            Modifying a calendar

            To perform an update of an calendar, you can provide the {@link android.provider.BaseColumns#_ID} of the calendar either as an appended ID to -the Uri +the Uri -({@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) +({@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) or as the first selection item. The selection should start with "_id=?", and the first selectionArg should be the {@link -android.provider.BaseColumns#_ID} of the calendar. +android.provider.BaseColumns#_ID} of the calendar. You can also do updates by encoding the ID in the URI. This example changes a -calendar's display name using the -({@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) +calendar's display name using the +({@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) approach:

            private static final String DEBUG_TAG = "MyActivity";
            @@ -375,7 +375,7 @@ an application needs to create a local calendar, it can do this by performing
             the calendar insertion as a sync adapter, using an {@link
             android.provider.CalendarContract.SyncColumns#ACCOUNT_TYPE} of {@link
             android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL}.
            -{@link android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL} 
            +{@link android.provider.CalendarContract#ACCOUNT_TYPE_LOCAL}
             is a special account type for calendars that are not
             associated with a device account. Calendars of this type are not synced to a server. For a
             discussion of sync adapters, see Sync Adapters.

            @@ -434,7 +434,7 @@ android.provider.CalendarContract.Events} reference.

            - + - + - + - - + + - + - + - + - - + - - - + @@ -519,11 +519,11 @@ you're inserting an event through the {@link android.content.Intent#ACTION_INSERT INSERT} Intent, described in Using an intent to insert an event—in that scenario, a default time zone is supplied. - +
          8. For non-recurring events, you must include {@link android.provider.CalendarContract.EventsColumns#DTEND}.
          9. - - + +
          10. For recurring events, you must include a {@link android.provider.CalendarContract.EventsColumns#DURATION} in addition to {@link android.provider.CalendarContract.EventsColumns#RRULE} or {@link @@ -532,9 +532,9 @@ you're inserting an event through the {@link android.content.Intent#ACTION_INSERT INSERT} Intent, described in Using an intent to insert an event—in that scenario, you can use an {@link -android.provider.CalendarContract.EventsColumns#RRULE} in conjunction with {@link android.provider.CalendarContract.EventsColumns#DTSTART} and {@link android.provider.CalendarContract.EventsColumns#DTEND}, and the Calendar application +android.provider.CalendarContract.EventsColumns#RRULE} in conjunction with {@link android.provider.CalendarContract.EventsColumns#DTSTART} and {@link android.provider.CalendarContract.EventsColumns#DTEND}, and the Calendar application converts it to a duration automatically.
          11. - +

            Here is an example of inserting an event. This is being performed in the UI @@ -545,8 +545,8 @@ information, see {@link android.content.AsyncQueryHandler}.

             long calID = 3;
            -long startMillis = 0; 
            -long endMillis = 0;     
            +long startMillis = 0;
            +long endMillis = 0;
             Calendar beginTime = Calendar.getInstance();
             beginTime.set(2012, 9, 14, 7, 30);
             startMillis = beginTime.getTimeInMillis();
            @@ -567,7 +567,7 @@ Uri uri = cr.insert(Events.CONTENT_URI, values);
             
             // get the event ID that is the last element in the Uri
             long eventID = Long.parseLong(uri.getLastPathSegment());
            -// 
            +//
             // ... do something with event ID
             //
             //
            @@ -584,14 +584,14 @@ attendees or reminders to an event.

            that you use an {@link android.content.Intent#ACTION_EDIT EDIT} Intent, as described in Using an intent to edit an event. However, if you need to, you can edit events directly. To perform an update of -an Event, you can provide the _ID of the +an Event, you can provide the _ID of the event either as an appended ID to the Uri ({@link -android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) -or as the first selection item. +android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()}) +or as the first selection item. The selection should start with "_id=?", and the first selectionArg should be the _ID of the event. You can also do updates using a selection with no ID. Here is an example of updating an -event. It changes the title of the event using the +event. It changes the title of the event using the {@link android.content.ContentUris#withAppendedId(android.net.Uri,long) withAppendedId()} approach:

            @@ -604,7 +604,7 @@ ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); Uri updateUri = null; // The new title for the event -values.put(Events.TITLE, "Kickboxing"); +values.put(Events.TITLE, "Kickboxing"); updateUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID); int rows = getContentResolver().update(updateUri, values, null, null); Log.i(DEBUG_TAG, "Rows updated: " + rows); @@ -631,22 +631,22 @@ ContentValues values = new ContentValues(); Uri deleteUri = null; deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID); int rows = getContentResolver().delete(deleteUri, null, null); -Log.i(DEBUG_TAG, "Rows deleted: " + rows); +Log.i(DEBUG_TAG, "Rows deleted: " + rows);

            Attendees Table

            Each row of the {@link android.provider.CalendarContract.Attendees} table -represents a single attendee or guest of an event. Calling -{@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} +represents a single attendee or guest of an event. Calling +{@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} returns a list of attendees for the -event with the given {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID}. -This {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} +event with the given {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID}. +This {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} must match the {@link -android.provider.BaseColumns#_ID} of a particular event.

            +android.provider.BaseColumns#_ID} of a particular event.

            The following table lists the -writable fields. When inserting a new attendee, you must include all of them +writable fields. When inserting a new attendee, you must include all of them except ATTENDEE_NAME.

            @@ -704,7 +704,7 @@ except ATTENDEE_NAME.

            Adding Attendees

            Here is an example that adds a single attendee to an event. Note that the -{@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} +{@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID} is required:

            @@ -724,17 +724,17 @@ Uri uri = cr.insert(Attendees.CONTENT_URI, values);
             

            Reminders Table

            Each row of the {@link android.provider.CalendarContract.Reminders} table -represents a single reminder for an event. Calling +represents a single reminder for an event. Calling {@link android.provider.CalendarContract.Reminders#query(android.content.ContentResolver, long, java.lang.String[]) query()} returns a list of reminders for the -event with the given +event with the given {@link android.provider.CalendarContract.AttendeesColumns#EVENT_ID}.

            The following table lists the writable fields for reminders. All of them must be included when inserting a new reminder. Note that sync adapters specify the types of reminders they support in the {@link -android.provider.CalendarContract.Calendars} table. See -{@link android.provider.CalendarContract.CalendarColumns#ALLOWED_REMINDERS} +android.provider.CalendarContract.Calendars} table. See +{@link android.provider.CalendarContract.CalendarColumns#ALLOWED_REMINDERS} for details.

            @@ -779,16 +779,16 @@ Uri uri = cr.insert(Reminders.CONTENT_URI, values);

            Instances Table

            -

            The +

            The {@link android.provider.CalendarContract.Instances} table holds the start and end time for occurrences of an event. Each row in this table represents a single event occurrence. The instances table is not writable and only provides a way to query event occurrences.

            -

            The following table lists some of the fields you can query on for an instance. Note -that time zone is defined by -{@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} -and +

            The following table lists some of the fields you can query on for an instance. Note +that time zone is defined by +{@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_TYPE} +and {@link android.provider.CalendarContract.CalendarCache#KEY_TIMEZONE_INSTANCES}.

            @@ -807,18 +807,18 @@ and - + - + - + @@ -826,16 +826,16 @@ Calendar's time zone. - - + - +
            {@link android.provider.CalendarContract.Calendars#VISIBLE}A boolean indicating whether the calendar is selected to be displayed. A value of 0 indicates that events associated with this calendar should not be shown. A value of 1 indicates that events associated with this calendar should @@ -240,7 +240,7 @@ android.provider.CalendarContract.Instances} table.
            {@link android.provider.CalendarContract.CalendarColumns#SYNC_EVENTS}A boolean indicating whether the calendar should be synced and have its events stored on the device. A value of 0 says do not sync this calendar or store its events on the device. A value of 1 says sync events for this calendar @@ -253,8 +253,8 @@ and store its events on the device.
            {@link android.provider.CalendarContract.EventsColumns#DURATION}The duration of the event in RFC5545 format. For example, a value of "PT1H" states that the event @@ -445,41 +445,41 @@ duration of 2 weeks.
            {@link android.provider.CalendarContract.EventsColumns#ALL_DAY}A value of 1 indicates this event occupies the entire day, as defined by the local time zone. A value of 0 indicates it is a regular event that may start and end at any time during a day.
            {@link android.provider.CalendarContract.EventsColumns#RRULE}The recurrence rule for the event format. For example, "FREQ=WEEKLY;COUNT=10;WKST=SU". You can find more examples here.
            {@link android.provider.CalendarContract.EventsColumns#RDATE}The recurrence dates for the event. - You typically use {@link android.provider.CalendarContract.EventsColumns#RDATE} - in conjunction with {@link android.provider.CalendarContract.EventsColumns#RRULE} + The recurrence dates for the event. + You typically use {@link android.provider.CalendarContract.EventsColumns#RDATE} + in conjunction with {@link android.provider.CalendarContract.EventsColumns#RRULE} to define an aggregate set of repeating occurrences. For more discussion, see the RFC5545 spec.
            {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY}If this event counts as busy time or is free time that can be + + If this event counts as busy time or is free time that can be scheduled over.
            {@link android.provider.CalendarContract.EventsColumns#GUESTS_CAN_MODIFY}
            {@link android.provider.CalendarContract.Instances#END_DAY}The Julian end day of the instance, relative to the Calendar's time -zone. - +zone. +
            {@link android.provider.CalendarContract.Instances#END_MINUTE}The end minute of the instance measured from midnight in the Calendar's time zone.
            {@link android.provider.CalendarContract.Instances#EVENT_ID}
            {@link android.provider.CalendarContract.Instances#START_DAY}The Julian start day of the instance, relative to the Calendar's time zone. + The Julian start day of the instance, relative to the Calendar's time zone.
            {@link android.provider.CalendarContract.Instances#START_MINUTE}The start minute of the instance measured from midnight, relative to the -Calendar's time zone. +Calendar's time zone.
            @@ -846,7 +846,7 @@ Calendar's time zone. in the URI. In this example, {@link android.provider.CalendarContract.Instances} gets access to the {@link android.provider.CalendarContract.EventsColumns#TITLE} field through its -implementation of the {@link android.provider.CalendarContract.EventsColumns} interface. +implementation of the {@link android.provider.CalendarContract.EventsColumns} interface. In other words, {@link android.provider.CalendarContract.EventsColumns#TITLE} is returned through a database view, not through querying the raw {@link @@ -859,7 +859,7 @@ public static final String[] INSTANCE_PROJECTION = new String[] { Instances.BEGIN, // 1 Instances.TITLE // 2 }; - + // The indices for the projection array above. private static final int PROJECTION_ID_INDEX = 0; private static final int PROJECTION_BEGIN_INDEX = 1; @@ -874,7 +874,7 @@ long startMillis = beginTime.getTimeInMillis(); Calendar endTime = Calendar.getInstance(); endTime.set(2011, 10, 24, 8, 0); long endMillis = endTime.getTimeInMillis(); - + Cursor cur = null; ContentResolver cr = getContentResolver(); @@ -889,28 +889,28 @@ ContentUris.appendId(builder, startMillis); ContentUris.appendId(builder, endMillis); // Submit the query -cur = cr.query(builder.build(), - INSTANCE_PROJECTION, - selection, - selectionArgs, +cur = cr.query(builder.build(), + INSTANCE_PROJECTION, + selection, + selectionArgs, null); - + while (cur.moveToNext()) { String title = null; long eventID = 0; - long beginVal = 0; - + long beginVal = 0; + // Get the field values eventID = cur.getLong(PROJECTION_ID_INDEX); beginVal = cur.getLong(PROJECTION_BEGIN_INDEX); title = cur.getString(PROJECTION_TITLE_INDEX); - - // Do something with the values. - Log.i(DEBUG_TAG, "Event: " + title); + + // Do something with the values. + Log.i(DEBUG_TAG, "Event: " + title); Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(beginVal); + calendar.setTimeInMillis(beginVal); DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); - Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); + Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime())); } }
          12. @@ -928,9 +928,9 @@ while (cur.moveToNext()) {
            {@link android.content.Intent#ACTION_VIEW VIEW}

            content://com.android.calendar/time/<ms_since_epoch>

            - You can also refer to the URI with -{@link android.provider.CalendarContract#CONTENT_URI CalendarContract.CONTENT_URI}. -For an example of using this intent, see Using intents to view calendar data. + You can also refer to the URI with +{@link android.provider.CalendarContract#CONTENT_URI CalendarContract.CONTENT_URI}. +For an example of using this intent, see Using intents to view calendar data. Open calendar to the time specified by <ms_since_epoch>. @@ -941,11 +941,11 @@ For an example of using this intent, see Using intents to view calendar data. - + View the event specified by <event_id>. @@ -958,12 +958,12 @@ For an example of using this intent, see Using an intent to edit an event. - - + + Edit the event specified by <event_id>. @@ -978,11 +978,11 @@ For an example of using this intent, see Using an intent to insert an event. - + Create an event. @@ -1002,7 +1002,7 @@ For an example of using this intent, see manifest file.

            - +

            When users run an application that uses this approach, the application sends them to the Calendar to finish adding the event. The {@link android.content.Intent#ACTION_INSERT INSERT} Intent uses extra fields to pre-populate a form with the details of the event in the Calendar. Users can then cancel the event, edit the form as needed, or save the event to their calendars.

            - +

            Here is a code snippet that schedules an event on January 19, 2012, that runs from 7:30 a.m. to 8:30 a.m. Note the following about this code snippet:

              -
            • It specifies {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} +
            • It specifies {@link android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} as the Uri.
            • - +
            • It uses the {@link android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME} and {@link @@ -1090,10 +1090,10 @@ android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME} extra fields to pre-populate the form with the time of the event. The values for these times must be in UTC milliseconds from the epoch.
            • - +
            • It uses the {@link android.content.Intent#EXTRA_EMAIL Intent.EXTRA_EMAIL} extra field to provide a comma-separated list of invitees, specified by email address.
            • - +
             Calendar beginTime = Calendar.getInstance();
            @@ -1166,18 +1166,18 @@ access the Calendar Provider:

            • A sync adapter needs to specify that it's a sync adapter by setting {@link android.provider.CalendarContract#CALLER_IS_SYNCADAPTER} to true.
            • - - + +
            • A sync adapter needs to provide an {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_NAME} and an {@link android.provider.CalendarContract.SyncColumns#ACCOUNT_TYPE} as query parameters in the URI.
            • - +
            • A sync adapter has write access to more columns than an application or widget. - For example, an application can only modify a few characteristics of a calendar, + For example, an application can only modify a few characteristics of a calendar, such as its name, display name, visibility setting, and whether the calendar is synced. By comparison, a sync adapter can access not only those columns, but many others, such as calendar color, time zone, access level, location, and so on. -However, a sync adapter is restricted to the ACCOUNT_NAME and +However, a sync adapter is restricted to the ACCOUNT_NAME and ACCOUNT_TYPE it specified.

            Here is a helper method you can use to return a URI for use with a sync adapter:

            @@ -1188,5 +1188,5 @@ However, a sync adapter is restricted to the ACCOUNT_NAME and .appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build(); }
            -

            For a sample implementation of a sync adapter (not specifically related to Calendar), see +

            For a sample implementation of a sync adapter (not specifically related to Calendar), see SampleSyncAdapter. diff --git a/docs/html/guide/topics/providers/content-provider-basics.jd b/docs/html/guide/topics/providers/content-provider-basics.jd index b7ae3d2cb85cf..37df4e92c66e8 100644 --- a/docs/html/guide/topics/providers/content-provider-basics.jd +++ b/docs/html/guide/topics/providers/content-provider-basics.jd @@ -238,7 +238,7 @@ page.title=Content Provider Basics For example, to get a list of the words and their locales from the User Dictionary Provider, you call {@link android.content.ContentResolver#query ContentResolver.query()}. The {@link android.content.ContentResolver#query query()} method calls the - {@link android.content.ContentProvider#query ContentProvider.query()} method defined by the + {@link android.content.ContentProvider#query ContentProvider.query()} method defined by the User Dictionary Provider. The following lines of code show a {@link android.content.ContentResolver#query ContentResolver.query()} call:

            @@ -253,7 +253,7 @@ mCursor = getContentResolver().query(

        12. Table 2 shows how the arguments to - {@link android.content.ContentResolver#query + {@link android.content.ContentResolver#query query(Uri,projection,selection,selectionArgs,sortOrder)} match an SQL SELECT statement:

          @@ -361,8 +361,8 @@ Uri singleUri = ContentUris.withAppendedId(UserDictionary.Words.CONTENT_URI,4);

          For the sake of clarity, the code snippets in this section call - {@link android.content.ContentResolver#query ContentResolver.query()} on the "UI thread"". In - actual code, however, you should do queries asynchronously on a separate thread. One way to do + {@link android.content.ContentResolver#query ContentResolver.query()} on the "UI thread"". In + actual code, however, you should do queries asynchronously on a separate thread. One way to do this is to use the {@link android.content.CursorLoader} class, which is described in more detail in the Loaders guide. Also, the lines of code are snippets only; they don't show a complete @@ -430,7 +430,7 @@ String[] mSelectionArgs = {""};

          The next snippet shows how to use {@link android.content.ContentResolver#query ContentResolver.query()}, using the User Dictionary - Provider as an example. A provider client query is similar to an SQL query, and it contains a + Provider as an example. A provider client query is similar to an SQL query, and it contains a set of columns to return, a set of selection criteria, and a sort order.

          @@ -440,8 +440,8 @@ String[] mSelectionArgs = {""};

          The expression that specifies the rows to retrieve is split into a selection clause and selection arguments. The selection clause is a combination of logical and Boolean expressions, - column names, and values (the variable mSelectionClause). If you specify the - replaceable parameter ? instead of a value, the query method retrieves the value + column names, and values (the variable mSelectionClause). If you specify the + replaceable parameter ? instead of a value, the query method retrieves the value from the selection arguments array (the variable mSelectionArgs).

          @@ -567,14 +567,14 @@ selectionArgs[0] = mUserInput;

          Displaying query results

          - The {@link android.content.ContentResolver#query ContentResolver.query()} client method always - returns a {@link android.database.Cursor} containing the columns specified by the query's - projection for the rows that match the query's selection criteria. A - {@link android.database.Cursor} object provides random read access to the rows and columns it - contains. Using {@link android.database.Cursor} methods, you can iterate over the rows in the + The {@link android.content.ContentResolver#query ContentResolver.query()} client method always + returns a {@link android.database.Cursor} containing the columns specified by the query's + projection for the rows that match the query's selection criteria. A + {@link android.database.Cursor} object provides random read access to the rows and columns it + contains. Using {@link android.database.Cursor} methods, you can iterate over the rows in the results, determine the data type of each column, get the data out of a column, and examine other - properties of the results. Some {@link android.database.Cursor} implementations automatically - update the object when the provider's data changes, or trigger methods in an observer object + properties of the results. Some {@link android.database.Cursor} implementations automatically + update the object when the provider's data changes, or trigger methods in an observer object when the {@link android.database.Cursor} changes, or both.

          @@ -705,14 +705,14 @@ if (mCursor != null) {

          To get the permissions needed to access a provider, an application requests them with a <uses-permission> - element in its manifest file. When the Android Package Manager installs the application, a user - must approve all of the permissions the application requests. If the user approves all of them, + element in its manifest file. When the Android Package Manager installs the application, a user + must approve all of the permissions the application requests. If the user approves all of them, Package Manager continues the installation; if the user doesn't approve them, Package Manager aborts the installation.

          The following -<uses-permission> +<uses-permission> element requests read access to the User Dictionary Provider:

          @@ -795,8 +795,8 @@ content://user_dictionary/words/<id_value>
               To update a row, you use a {@link android.content.ContentValues} object with the updated
               values just as you do with an insertion, and selection criteria just as you do with a query.
               The client method you use is
          -    {@link android.content.ContentResolver#update ContentResolver.update()}. You only need to add 
          -    values to the {@link android.content.ContentValues} object for columns you're updating. If you 
          +    {@link android.content.ContentResolver#update ContentResolver.update()}. You only need to add
          +    values to the {@link android.content.ContentValues} object for columns you're updating. If you
               want to clear the contents of a column, set the value to null.
           

          @@ -830,7 +830,7 @@ mRowsUpdated = getContentResolver().update(

          You should also sanitize user input when you call - {@link android.content.ContentResolver#update ContentResolver.update()}. To learn more about + {@link android.content.ContentResolver#update ContentResolver.update()}. To learn more about this, read the section Protecting against malicious input.

          Deleting data

          @@ -860,7 +860,7 @@ mRowsDeleted = getContentResolver().delete(

          You should also sanitize user input when you call - {@link android.content.ContentResolver#delete ContentResolver.delete()}. To learn more about + {@link android.content.ContentResolver#delete ContentResolver.delete()}. To learn more about this, read the section Protecting against malicious input.

          @@ -948,9 +948,9 @@ mRowsDeleted = getContentResolver().delete( To access a provider in "batch mode", you create an array of {@link android.content.ContentProviderOperation} objects and then dispatch them to a content provider with - {@link android.content.ContentResolver#applyBatch ContentResolver.applyBatch()}. You pass the - content provider's authority to this method, rather than a particular content URI. - This allows each {@link android.content.ContentProviderOperation} object in the array to work + {@link android.content.ContentResolver#applyBatch ContentResolver.applyBatch()}. You pass the + content provider's authority to this method, rather than a particular content URI. + This allows each {@link android.content.ContentProviderOperation} object in the array to work against a different table. A call to {@link android.content.ContentResolver#applyBatch ContentResolver.applyBatch()} returns an array of results.

          @@ -1013,7 +1013,7 @@ mRowsDeleted = getContentResolver().delete(

          A provider defines URI permissions for content URIs in its manifest, using the android:grantUriPermission - attribute of the + attribute of the <provider> element, as well as the <grant-uri-permission> diff --git a/docs/html/guide/topics/providers/content-provider-creating.jd b/docs/html/guide/topics/providers/content-provider-creating.jd index baa92e131dc74..ec6909c891368 100755 --- a/docs/html/guide/topics/providers/content-provider-creating.jd +++ b/docs/html/guide/topics/providers/content-provider-creating.jd @@ -422,7 +422,7 @@ public class ExampleProvider extends ContentProvider { * in the path */ sUriMatcher.addURI("com.example.app.provider", "table3", 1); - + /* * Sets the code for a single row to 2. In this case, the "#" wildcard is * used. "content://com.example.app.provider/table3/3" matches, but @@ -881,7 +881,7 @@ vnd.android.cursor.item/vnd.com.example.provider.table1 A contract class also helps developers because it usually has mnemonic names for its constants, so developers are less likely to use incorrect values for column names or URIs. Since it's a class, it can contain Javadoc documentation. Integrated development environments such as - Android Studio can auto-complete constant names from the contract class and display Javadoc for + Android Studio can auto-complete constant names from the contract class and display Javadoc for the constants.

          diff --git a/docs/html/guide/topics/renderscript/compute.jd b/docs/html/guide/topics/renderscript/compute.jd index fc795ff6a63f0..861c9258f2c25 100755 --- a/docs/html/guide/topics/renderscript/compute.jd +++ b/docs/html/guide/topics/renderscript/compute.jd @@ -167,7 +167,7 @@ precision (such as SIMD CPU instructions).

      We strongly recommend using the Support Library APIs for accessing RenderScript because they - provide a wider range of device compatibility. Developers targeting specific versions of + provide a wider range of device compatibility. Developers targeting specific versions of Android can use {@link android.renderscript} if necessary.

      diff --git a/docs/html/guide/topics/resources/accessing-resources.jd b/docs/html/guide/topics/resources/accessing-resources.jd index b971238c17732..953b27418efcb 100644 --- a/docs/html/guide/topics/resources/accessing-resources.jd +++ b/docs/html/guide/topics/resources/accessing-resources.jd @@ -264,8 +264,8 @@ reference a system resource, you would need to include the package name. For exa android:text="@string/hello" /> -

      Note: You should use string resources at -all times, so that your application can be localized for other languages. +

      Note: You should use string resources at +all times, so that your application can be localized for other languages. For information about creating alternative resources (such as localized strings), see Providing Alternative diff --git a/docs/html/guide/topics/resources/animation-resource.jd b/docs/html/guide/topics/resources/animation-resource.jd index e5cac8874afb9..05582f0e366d2 100644 --- a/docs/html/guide/topics/resources/animation-resource.jd +++ b/docs/html/guide/topics/resources/animation-resource.jd @@ -12,7 +12,7 @@ parent.link=available-resources.html

      1. Tween animation
      2. Frame animation
      3. -
      +
    • See also

      @@ -94,7 +94,7 @@ In XML: @[package:]animator/filename </set> -

      The file must have a single root element: either +

      The file must have a single root element: either <set>, <objectAnimator>, or <valueAnimator>. You can group animation elements together inside the <set> element, including other <set> elements. @@ -109,7 +109,7 @@ group animation elements together inside the <set> element, i <valueAnimator>, or other <set> elements). Represents an {@link android.animation.AnimatorSet}.

      You can specify nested <set> tags to further - group animations together. Each <set> can define its own + group animations together. Each <set> can define its own ordering attribute.

      attributes:

      @@ -119,11 +119,11 @@ group animation elements together inside the <set> element, i
      Keyword. Specifies the play ordering of animations in this set. - - - - -
      ValueDescription
      sequentiallyPlay animations in this set sequentially
      together (default)Play animations in this set at the same time.
      + + + + +
      ValueDescription
      sequentiallyPlay animations in this set sequentially
      together (default)Play animations in this set at the same time.
      @@ -131,11 +131,11 @@ group animation elements together inside the <set> element, i
      <objectAnimator>
      Animates a specific property of an object over a specific amount of time. Represents an {@link android.animation.ObjectAnimator}.

      - +

      attributes:

      - android:propertyName + android:propertyName
      String. Required. The object's property to animate, referenced by its name. For example you can specify @@ -206,11 +206,11 @@ group animation elements together inside the <set> element, i
      Keyword. Do not specify this attribute if the value is a color. The animation framework automatically handles color values - - - - -
      ValueDescription
      intTypeSpecifies that the animated values are integers
      floatType (default)Specifies that the animated values are floats
      + + + + +
      ValueDescription
      intTypeSpecifies that the animated values are integers
      floatType (default)Specifies that the animated values are floats
      @@ -279,11 +279,11 @@ group animation elements together inside the <set> element, i
      Keyword. Do not specify this attribute if the value is a color. The animation framework automatically handles color values. - - - - -
      ValueDescription
      intTypeSpecifies that the animated values are integers
      floatType (default)Specifies that the animated values are floats
      + + + + +
      ValueDescription
      intTypeSpecifies that the animated values are integers
      floatType (default)Specifies that the animated values are floats
      @@ -320,7 +320,7 @@ group animation elements together inside the <set> element, i before starting the animation set. Calling {@link android.animation.AnimatorSet#setTarget setTarget()} sets a single target object for all children of the {@link android.animation.AnimatorSet} as a convenience. The following code shows how to do this:

      - +
       AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(myContext,
           R.anim.property_animator);
      diff --git a/docs/html/guide/topics/resources/more-resources.jd b/docs/html/guide/topics/resources/more-resources.jd
      index 1afbf70731e40..8488cdee76205 100644
      --- a/docs/html/guide/topics/resources/more-resources.jd
      +++ b/docs/html/guide/topics/resources/more-resources.jd
      @@ -760,7 +760,7 @@ int color = colors.{@link android.content.res.TypedArray#getColor(int,int) getCo
           
       
       
      - 
      +
       
       
      example:
      @@ -781,7 +781,7 @@ int color = colors.{@link android.content.res.TypedArray#getColor(int,int) getCo
      - +
      see also:
      diff --git a/docs/html/guide/topics/resources/providing-resources.jd b/docs/html/guide/topics/resources/providing-resources.jd index c919ed5e777dd..80a989a57e284 100644 --- a/docs/html/guide/topics/resources/providing-resources.jd +++ b/docs/html/guide/topics/resources/providing-resources.jd @@ -523,7 +523,7 @@ is larger than the current screen, the system will not application will crash at runtime (for example, if all layout resources are tagged with the {@code xlarge} qualifier, but the device is a normal-size screen).

      Added in API level 4.

      - +

      See Supporting Multiple Screens for more information.

      Also see the {@link android.content.res.Configuration#screenLayout} configuration field, @@ -608,7 +608,7 @@ which indicates the current device orientation.

    Added in API level 8, television added in API 13, watch added in API 20.

    For information about how your app can respond when the device is inserted into or - removed from a dock, read Determining and Monitoring the Docking State and Type.

    This can change during the life of your application if the user places the device in a @@ -659,8 +659,8 @@ application during runtime.

    Level 8
  • {@code xxhdpi}: Extra-extra-high-density screens; approximately 480dpi. Added in API Level 16
  • -
  • {@code xxxhdpi}: Extra-extra-extra-high-density uses (launcher icon only, see the - note +
  • {@code xxxhdpi}: Extra-extra-extra-high-density uses (launcher icon only, see the + note in Supporting Multiple Screens); approximately 640dpi. Added in API Level 18
  • {@code nodpi}: This can be used for bitmap resources that you do not want to be scaled diff --git a/docs/html/guide/topics/resources/runtime-changes.jd b/docs/html/guide/topics/resources/runtime-changes.jd index 8781d208d6eac..2e6f9b765edf8 100644 --- a/docs/html/guide/topics/resources/runtime-changes.jd +++ b/docs/html/guide/topics/resources/runtime-changes.jd @@ -84,12 +84,12 @@ your activity to preserve stateful objects.

    To retain stateful objects in a fragment during a runtime configuration change:

      -
    1. Extend the {@link android.app.Fragment} class and declare references to your stateful +
    2. Extend the {@link android.app.Fragment} class and declare references to your stateful objects.
    3. Call {@link android.app.Fragment#setRetainInstance(boolean)} when the fragment is created.
    4. Add the fragment to your activity.
    5. -
    6. Use {@link android.app.FragmentManager} to retrieve the fragment when the activity is +
    7. Use {@link android.app.FragmentManager} to retrieve the fragment when the activity is restarted.
    @@ -127,8 +127,8 @@ leak all the views and resources of the original activity instance. (Leaking res means that your application maintains a hold on them and they cannot be garbage-collected, so lots of memory can be lost.)

    -

    Then use {@link android.app.FragmentManager} to add the fragment to the activity. -You can obtain the data object from the fragment when the activity starts again during runtime +

    Then use {@link android.app.FragmentManager} to add the fragment to the activity. +You can obtain the data object from the fragment when the activity starts again during runtime configuration changes. For example, define your activity as follows:

    @@ -170,7 +170,7 @@ public class MyActivity extends Activity {
     

    In this example, {@link android.app.Activity#onCreate(Bundle) onCreate()} adds a fragment or restores a reference to it. {@link android.app.Activity#onCreate(Bundle) onCreate()} also stores the stateful object inside the fragment instance. -{@link android.app.Activity#onDestroy() onDestroy()} updates the stateful object inside the +{@link android.app.Activity#onDestroy() onDestroy()} updates the stateful object inside the retained fragment instance.

    diff --git a/docs/html/guide/topics/sensors/index.jd b/docs/html/guide/topics/sensors/index.jd index 09d27e7a9bd59..36d3adcb48a3d 100644 --- a/docs/html/guide/topics/sensors/index.jd +++ b/docs/html/guide/topics/sensors/index.jd @@ -1,7 +1,7 @@ page.title=Location and Sensors APIs page.landing=true page.tags=location,sensors -page.landing.intro=Use sensors on the device to add rich location and motion capabilities to your app, from GPS or network location to accelerometer, gyroscope, temperature, barometer, and more. +page.landing.intro=Use sensors on the device to add rich location and motion capabilities to your app, from GPS or network location to accelerometer, gyroscope, temperature, barometer, and more. page.landing.image= @jd:body @@ -10,7 +10,7 @@ page.landing.image=

    Blog Articles

    - +

    One Screen Turn Deserves Another

    However, there’s a new wrinkle: recently, a few devices have shipped (see here and here) @@ -18,7 +18,7 @@ that run Android on screens that are naturally landscape in their orientation. T the default position, the screens are wider than they are tall. This introduces a few fairly subtle issues that we’ve noticed causing problems in some apps.

    - +

    A Deep Dive Into Location

    I’ve written an open-source reference app that incorporates all of the tips, tricks, and @@ -29,7 +29,7 @@ venues - as well as providing a reasonable level of offline support

    Training

    - +

    Making Your App Location Aware

    This class teaches you how to incorporate location based services in your Android diff --git a/docs/html/guide/topics/text/index.jd b/docs/html/guide/topics/text/index.jd index 3865f25aee714..2bf46967339e8 100644 --- a/docs/html/guide/topics/text/index.jd +++ b/docs/html/guide/topics/text/index.jd @@ -9,7 +9,7 @@ page.landing.image=

    - The Android platform offers a spelling checker framework that lets you implement - and access spell checking in your application. The framework is one of the + The Android platform offers a spelling checker framework that lets you implement + and access spell checking in your application. The framework is one of the Text Service APIs offered by the Android platform.

    - To use the framework in your app, you create a special type of Android service that + To use the framework in your app, you create a special type of Android service that generates a spelling checker session object. Based on text you provide, the session object returns spelling suggestions generated by the spelling checker.

    diff --git a/docs/html/guide/topics/ui/accessibility/apps.jd b/docs/html/guide/topics/ui/accessibility/apps.jd index eb639e37027d3..26fb3cca9dc3d 100644 --- a/docs/html/guide/topics/ui/accessibility/apps.jd +++ b/docs/html/guide/topics/ui/accessibility/apps.jd @@ -458,7 +458,7 @@ public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { // Call the super implementation to populate its text to the event, which // calls onPopulateAccessibilityEvent() on API Level 14 and up. boolean completed = super.dispatchPopulateAccessibilityEvent(event); - + // In case this is running on a API revision earlier that 14, check // the text content of the event and add an appropriate text // description for this custom view: diff --git a/docs/html/guide/topics/ui/binding.jd b/docs/html/guide/topics/ui/binding.jd index a4fd25c2825e9..48a1d409ef21e 100644 --- a/docs/html/guide/topics/ui/binding.jd +++ b/docs/html/guide/topics/ui/binding.jd @@ -16,7 +16,7 @@ parent.link=index.html
    -// Get a Spinner and bind it to an ArrayAdapter that 
    +// Get a Spinner and bind it to an ArrayAdapter that
     // references a String array.
     Spinner s1 = (Spinner) findViewById(R.id.spinner1);
     ArrayAdapter adapter = ArrayAdapter.createFromResource(
    @@ -31,7 +31,7 @@ private static String[] PROJECTION = new String[] {
     
     Spinner s2 = (Spinner) findViewById(R.id.spinner2);
     Cursor cur = managedQuery(People.CONTENT_URI, PROJECTION, null, null);
    -     
    +
     SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(this,
         android.R.layout.simple_spinner_item, // Use a template
                                               // that displays a
    @@ -41,7 +41,7 @@ SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(this,
                                              // people database to...
         new int[] {android.R.id.text1}); // The "text1" view defined in
                                          // the XML template
    -					 
    +
     adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     s2.setAdapter(adapter2);
     
    @@ -70,7 +70,7 @@ private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() { // Now hook into our object and set its onItemClickListener member // to our class handler object. mHistoryView = (ListView)findViewById(R.id.history); -mHistoryView.setOnItemClickListener(mMessageClickedHandler); +mHistoryView.setOnItemClickListener(mMessageClickedHandler);
    diff --git a/docs/html/guide/topics/ui/controls.jd b/docs/html/guide/topics/ui/controls.jd index a58d9f9b380f3..bb8c1a7795888 100644 --- a/docs/html/guide/topics/ui/controls.jd +++ b/docs/html/guide/topics/ui/controls.jd @@ -71,7 +71,7 @@ href="{@docRoot}guide/topics/ui/custom-components.html">custom components. Radio button Similar to checkboxes, except that only one option can be selected in the group. - {@link android.widget.RadioGroup RadioGroup} + {@link android.widget.RadioGroup RadioGroup}
    {@link android.widget.RadioButton RadioButton} diff --git a/docs/html/guide/topics/ui/controls/button.jd b/docs/html/guide/topics/ui/controls/button.jd index 295044f0b55d0..a529d533de793 100644 --- a/docs/html/guide/topics/ui/controls/button.jd +++ b/docs/html/guide/topics/ui/controls/button.jd @@ -214,7 +214,7 @@ pressed (activated).
  • The second <item> defines the bitmap to use when the button is focused (when the button is highlighted using the trackball or directional pad).
  • -
  • The third <item> defines the bitmap to use when the button is in the +
  • The third <item> defines the bitmap to use when the button is in the default state (it's neither pressed nor focused).
  • Note: The order of the <item> elements is diff --git a/docs/html/guide/topics/ui/controls/checkbox.jd b/docs/html/guide/topics/ui/controls/checkbox.jd index 2a64e38d3bf43..f5feeb106a380 100644 --- a/docs/html/guide/topics/ui/controls/checkbox.jd +++ b/docs/html/guide/topics/ui/controls/checkbox.jd @@ -65,7 +65,7 @@ click event for both checkboxes:

    public void onCheckboxClicked(View view) { // Is the view now checked? boolean checked = ((CheckBox) view).isChecked(); - + // Check which checkbox was clicked switch(view.getId()) { case R.id.checkbox_meat: diff --git a/docs/html/guide/topics/ui/controls/pickers.jd b/docs/html/guide/topics/ui/controls/pickers.jd index c0667add65aaa..9788f084022ae 100644 --- a/docs/html/guide/topics/ui/controls/pickers.jd +++ b/docs/html/guide/topics/ui/controls/pickers.jd @@ -123,15 +123,15 @@ android.support.v4.app.DialogFragment#show show()}.

    For example, here's a button that, when clicked, calls a method to show the dialog:

    -<Button 
    -    android:layout_width="wrap_content" 
    +<Button
    +    android:layout_width="wrap_content"
         android:layout_height="wrap_content"
    -    android:text="@string/pick_time" 
    +    android:text="@string/pick_time"
         android:onClick="showTimePickerDialog" />
     

    When the user clicks this button, the system calls the following method:

    - +
     public void showTimePickerDialog(View v) {
         DialogFragment newFragment = new TimePickerFragment();
    @@ -224,15 +224,15 @@ android.support.v4.app.DialogFragment#show show()}.

    For example, here's a button that, when clicked, calls a method to show the dialog:

    -<Button 
    -    android:layout_width="wrap_content" 
    +<Button
    +    android:layout_width="wrap_content"
         android:layout_height="wrap_content"
    -    android:text="@string/pick_date" 
    +    android:text="@string/pick_date"
         android:onClick="showDatePickerDialog" />
     

    When the user clicks this button, the system calls the following method:

    - +
     public void showDatePickerDialog(View v) {
         DialogFragment newFragment = new DatePickerFragment();
    diff --git a/docs/html/guide/topics/ui/controls/radiobutton.jd b/docs/html/guide/topics/ui/controls/radiobutton.jd
    index b2556e1956ab3..e1441d3f5fbff 100644
    --- a/docs/html/guide/topics/ui/controls/radiobutton.jd
    +++ b/docs/html/guide/topics/ui/controls/radiobutton.jd
    @@ -72,7 +72,7 @@ click event for both radio buttons:

    public void onRadioButtonClicked(View view) { // Is the button now checked? boolean checked = ((RadioButton) view).isChecked(); - + // Check which radio button was clicked switch(view.getId()) { case R.id.radio_pirates: diff --git a/docs/html/guide/topics/ui/controls/spinner.jd b/docs/html/guide/topics/ui/controls/spinner.jd index 3b8aaad4613c1..00b0432f9f708 100644 --- a/docs/html/guide/topics/ui/controls/spinner.jd +++ b/docs/html/guide/topics/ui/controls/spinner.jd @@ -4,7 +4,7 @@ page.tags=adapterview,spinneradapter
    - +

    In this document

    1. Populate the Spinner with User Choices
    2. @@ -113,8 +113,8 @@ For example, here's an implementation of the interface in an {@link android.app.
       public class SpinnerActivity extends Activity implements OnItemSelectedListener {
           ...
      -    
      -    public void onItemSelected(AdapterView<?> parent, View view, 
      +
      +    public void onItemSelected(AdapterView<?> parent, View view,
                   int pos, long id) {
               // An item was selected. You can retrieve the selected item using
               // parent.getItemAtPosition(pos)
      diff --git a/docs/html/guide/topics/ui/controls/text.jd b/docs/html/guide/topics/ui/controls/text.jd
      index f4d72b2a80f6f..f5c2a4251788d 100644
      --- a/docs/html/guide/topics/ui/controls/text.jd
      +++ b/docs/html/guide/topics/ui/controls/text.jd
      @@ -4,7 +4,7 @@ page.tags=edittext,autocompletetextview
       
       
      - +

      In this document

      1. Specifying the Keyboard Type @@ -279,7 +279,7 @@ that provides suggestions from an array, using {@link android.widget.ArrayAdapte layout with only the text field:
         <?xml version="1.0" encoding="utf-8"?>
        -<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android" 
        +<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android"
             android:id="@+id/autocomplete_country"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content" />
        @@ -313,8 +313,8 @@ code to specify the adapter that supplies the suggestions:
         AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
         // Get the string array
         String[] countries = getResources().getStringArray(R.array.countries_array);
        -// Create the adapter and set it to the AutoCompleteTextView 
        -ArrayAdapter<String> adapter = 
        +// Create the adapter and set it to the AutoCompleteTextView
        +ArrayAdapter<String> adapter =
                 new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
         textView.setAdapter(adapter);
         
        diff --git a/docs/html/guide/topics/ui/custom-components.jd b/docs/html/guide/topics/ui/custom-components.jd index b7249c56ea0ba..bd3de1c29a24e 100755 --- a/docs/html/guide/topics/ui/custom-components.jd +++ b/docs/html/guide/topics/ui/custom-components.jd @@ -14,37 +14,37 @@ page.tags=view,widget
      -

      Android offers a sophisticated and powerful componentized model for building your UI, -based on the fundamental layout classes: {@link android.view.View} and -{@link android.view.ViewGroup}. To start with, the platform includes a variety of prebuilt -View and ViewGroup subclasses — called widgets and layouts, respectively — +

      Android offers a sophisticated and powerful componentized model for building your UI, +based on the fundamental layout classes: {@link android.view.View} and +{@link android.view.ViewGroup}. To start with, the platform includes a variety of prebuilt +View and ViewGroup subclasses — called widgets and layouts, respectively — that you can use to construct your UI.

      -

      A partial list of available widgets includes {@link android.widget.Button Button}, -{@link android.widget.TextView TextView}, -{@link android.widget.EditText EditText}, +

      A partial list of available widgets includes {@link android.widget.Button Button}, +{@link android.widget.TextView TextView}, +{@link android.widget.EditText EditText}, {@link android.widget.ListView ListView}, -{@link android.widget.CheckBox CheckBox}, -{@link android.widget.RadioButton RadioButton}, -{@link android.widget.Gallery Gallery}, -{@link android.widget.Spinner Spinner}, and the more special-purpose -{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, +{@link android.widget.CheckBox CheckBox}, +{@link android.widget.RadioButton RadioButton}, +{@link android.widget.Gallery Gallery}, +{@link android.widget.Spinner Spinner}, and the more special-purpose +{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, {@link android.widget.ImageSwitcher ImageSwitcher}, and {@link android.widget.TextSwitcher TextSwitcher}.

      -

      Among the layouts available are {@link android.widget.LinearLayout LinearLayout}, -{@link android.widget.FrameLayout FrameLayout}, {@link android.widget.RelativeLayout RelativeLayout}, +

      Among the layouts available are {@link android.widget.LinearLayout LinearLayout}, +{@link android.widget.FrameLayout FrameLayout}, {@link android.widget.RelativeLayout RelativeLayout}, and others. For more examples, see Common Layout Objects.

      -

      If none of the prebuilt widgets or layouts meets your needs, you can create your own View subclass. -If you only need to make small adjustments to an existing widget or layout, you can simply subclass +

      If none of the prebuilt widgets or layouts meets your needs, you can create your own View subclass. +If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods.

      -

      Creating your own View subclasses gives you precise control over the appearance and function -of a screen element. To give an idea of the control you get with custom views, here are some +

      Creating your own View subclasses gives you precise control over the appearance and function +of a screen element. To give an idea of the control you get with custom views, here are some examples of what you could do with them:

      - +
      • You could create a completely custom-rendered View type, for example a "volume @@ -60,7 +60,7 @@ examples of what you could do with them:

      • You could override the way that an EditText component is rendered on the screen - (the Notepad Tutorial uses this to good effect, + (the Notepad Tutorial uses this to good effect, to create a lined-notepad page).
      • @@ -69,7 +69,7 @@ examples of what you could do with them:

      -The sections below explain how to create custom Views and use them in your application. +The sections below explain how to create custom Views and use them in your application. For detailed reference information, see the {@link android.view.View} class.

      @@ -77,26 +77,26 @@ For detailed reference information, see the {@link android.view.View} class.

      Here is a high level overview of what you need to know to get started in creating your own View components:

      - +
      1. - Extend an existing {@link android.view.View View} class or subclass + Extend an existing {@link android.view.View View} class or subclass with your own class.
      2. - Override some of the methods from the superclass. The superclass methods + Override some of the methods from the superclass. The superclass methods to override start with 'on', for - example, {@link android.view.View#onDraw onDraw()}, - {@link android.view.View#onMeasure onMeasure()}, and + example, {@link android.view.View#onDraw onDraw()}, + {@link android.view.View#onMeasure onMeasure()}, and {@link android.view.View#onKeyDown onKeyDown()}. - This is similar to the on... events in {@link android.app.Activity Activity} + This is similar to the on... events in {@link android.app.Activity Activity} or {@link android.app.ListActivity ListActivity} that you override for lifecycle and other functionality hooks.
      3. - Use your new extension class. Once completed, your new extension class + Use your new extension class. Once completed, your new extension class can be used in place of the view upon which it was based.
      4. -
      +

    Tip: Extension classes can be defined as inner classes inside the activities that use them. This is useful because it controls access to them but @@ -119,7 +119,7 @@ way you like, limited perhaps only by your imagination, the size of the screen, and the available processing power (remember that ultimately your application might have to run on something with significantly less power than your desktop workstation).

    -

    To create a fully customized component:

    +

    To create a fully customized component:

    1. The most generic view you can extend is, unsurprisingly, {@link @@ -170,11 +170,11 @@ slightly more complex by the requirements of limits from the parent (which are passed in to the onMeasure() method) and by the requirement to call the setMeasuredDimension() method with the measured width and height once they have been calculated. If you fail to -call this method from an overridden onMeasure() method, the +call this method from an overridden onMeasure() method, the result will be an exception at measurement time.

      -

      At a high level, implementing onMeasure() looks something +

      At a high level, implementing onMeasure() looks something like this:

      - +
      1. The overridden onMeasure() method is called with width and @@ -193,7 +193,7 @@ result will be an exception at measurement time.

        measurement width and height which will be required to render the component. It should try to stay within the specifications passed in, although it can choose to exceed them (in this case, the parent can - choose what to do, including clipping, scrolling, throwing an exception, + choose what to do, including clipping, scrolling, throwing an exception, or asking the onMeasure() to try again, perhaps with different measurement specifications).
      2. @@ -212,7 +212,7 @@ Here's a summary of some of the other standard methods that the framework calls Category Methods Description - + Creation @@ -228,7 +228,7 @@ Here's a summary of some of the other standard methods that the framework calls Called after a view and all of its children has been inflated from XML. - + Layout {@link android.view.View#onMeasure} @@ -247,14 +247,14 @@ Here's a summary of some of the other standard methods that the framework calls Called when the size of this view has changed. - + Drawing {@link android.view.View#onDraw} Called when the view should render its content. - + Event processing {@link android.view.View#onKeyDown} @@ -265,58 +265,58 @@ Here's a summary of some of the other standard methods that the framework calls {@link android.view.View#onKeyUp} Called when a key up event occurs. - + {@link android.view.View#onTrackballEvent} Called when a trackball motion event occurs. - + {@link android.view.View#onTouchEvent} Called when a touch screen motion event occurs. - - + + Focus {@link android.view.View#onFocusChanged} Called when the view gains or loses focus. - + {@link android.view.View#onWindowFocusChanged} Called when the window containing the view gains or loses focus. - + Attaching {@link android.view.View#onAttachedToWindow()} Called when the view is attached to a window. - + {@link android.view.View#onDetachedFromWindow} Called when the view is detached from its window. - - + + {@link android.view.View#onWindowVisibilityChanged} Called when the visibility of the window containing the view has changed. - + - +

        A Custom View Example

        -

        The CustomView sample in the +

        The CustomView sample in the API Demos provides an example of a customized View. The custom View is defined in the LabelView @@ -359,9 +359,9 @@ combination of a single line EditText field and an adjacent button with an attac something from the list, it populates the EditText field, but the user can also type something directly into the EditText if they prefer.

        In Android, there are actually two other Views readily available to do -this: {@link android.widget.Spinner Spinner} and -{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, but -regardless, the concept of a Combo Box makes an easy-to-understand +this: {@link android.widget.Spinner Spinner} and +{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, but +regardless, the concept of a Combo Box makes an easy-to-understand example.

        To create a compound component:

          @@ -397,7 +397,7 @@ example.

        1. In the case of extending a Layout, you don't need to override the onDraw() and onMeasure() methods since the - layout will have default behavior that will likely work just fine. However, + layout will have default behavior that will likely work just fine. However, you can still override them if you need to.
        2. @@ -409,7 +409,7 @@ example.

          To summarize, the use of a Layout as the basis for a Custom Control has a number of advantages, including:

          - +
        - +

        See also

        1. Dialogs design guide
        2. @@ -238,8 +238,8 @@ AlertDialog dialog = builder.create();

    The set...Button() methods require a title for the button (supplied -by a string resource) and a -{@link android.content.DialogInterface.OnClickListener} that defines the action to take +by a string resource) and a +{@link android.content.DialogInterface.OnClickListener} that defines the action to take when the user presses the button.

    There are three different action buttons you can add:

    @@ -251,7 +251,7 @@ when the user presses the button.

    Neutral
    You should use this when the user may not want to proceed with the action, but doesn't necessarily want to cancel. It appears between the positive and negative - buttons. For example, the action might be "Remind me later."
    + buttons. For example, the action might be "Remind me later."

    You can add only one of each button type to an {@link @@ -274,7 +274,7 @@ A dialog with a title and list.

  • A persistent multiple-choice list (checkboxes)
  • -

    To create a single-choice list like the one in figure 3, +

    To create a single-choice list like the one in figure 3, use the {@link android.app.AlertDialog.Builder#setItems setItems()} method:

    @@ -294,7 +294,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
     
     

    Because the list appears in the dialog's content area, the dialog cannot show both a message and a list and you should set a title for the -dialog with {@link android.app.AlertDialog.Builder#setTitle setTitle()}. +dialog with {@link android.app.AlertDialog.Builder#setTitle setTitle()}. To specify the items for the list, call {@link android.app.AlertDialog.Builder#setItems setItems()}, passing an array. Alternatively, you can specify a list using {@link @@ -320,11 +320,11 @@ A list of multiple-choice items.

    Adding a persistent multiple-choice or single-choice list

    -

    To add a list of multiple-choice items (checkboxes) or +

    To add a list of multiple-choice items (checkboxes) or single-choice items (radio buttons), use the {@link android.app.AlertDialog.Builder#setMultiChoiceItems(Cursor,String,String, -DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} or -{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} or +{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()} methods, respectively.

    For example, here's how you can create a multiple-choice list like the @@ -349,7 +349,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { // If the user checked the item, add it to the selected items mSelectedItems.add(which); } else if (mSelectedItems.contains(which)) { - // Else, if the item is already in the array, remove it + // Else, if the item is already in the array, remove it mSelectedItems.remove(Integer.valueOf(which)); } } @@ -376,7 +376,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {

    Although both a traditional list and a list with radio buttons provide a "single choice" action, you should use {@link -android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) setSingleChoiceItems()} if you want to persist the user's choice. That is, if opening the dialog again later should indicate what the user's current choice is, then you create a list with radio buttons.

    @@ -445,7 +445,7 @@ you should change its font family to {@code "sans-serif"} so that both text fiel a matching font style.

    To inflate the layout in your {@link android.support.v4.app.DialogFragment}, -get a {@link android.view.LayoutInflater} with +get a {@link android.view.LayoutInflater} with {@link android.app.Activity#getLayoutInflater()} and call {@link android.view.LayoutInflater#inflate inflate()}, where the first parameter is the layout resource ID and the second parameter is a parent view for the layout. @@ -473,7 +473,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { public void onClick(DialogInterface dialog, int id) { LoginDialogFragment.this.getDialog().cancel(); } - }); + }); return builder.create(); }

    @@ -508,7 +508,7 @@ interface through which it delivers the events back to the host activity:

     public class NoticeDialogFragment extends DialogFragment {
    -    
    +
         /* The activity that creates an instance of this dialog fragment must
          * implement this interface in order to receive event callbacks.
          * Each method passes the DialogFragment in case the host needs to query it. */
    @@ -516,10 +516,10 @@ public class NoticeDialogFragment extends DialogFragment {
             public void onDialogPositiveClick(DialogFragment dialog);
             public void onDialogNegativeClick(DialogFragment dialog);
         }
    -    
    +
         // Use this instance of the interface to deliver action events
         NoticeDialogListener mListener;
    -    
    +
         // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
         @Override
         public void onAttach(Activity activity) {
    @@ -546,7 +546,7 @@ events through an implementation of the {@code NoticeDialogListener} interface:<
     public class MainActivity extends FragmentActivity
                               implements NoticeDialogFragment.NoticeDialogListener{
         ...
    -    
    +
         public void showNoticeDialog() {
             // Create an instance of the dialog fragment and show it
             DialogFragment dialog = new NoticeDialogFragment();
    @@ -659,7 +659,7 @@ public class CustomDialogFragment extends DialogFragment {
             // Inflate the layout to use as dialog or embedded fragment
             return inflater.inflate(R.layout.purchase_items, container, false);
         }
    -  
    +
         /** The system calls this only when creating the layout in a dialog. */
         @Override
         public Dialog onCreateDialog(Bundle savedInstanceState) {
    @@ -681,7 +681,7 @@ or a fullscreen UI, based on the screen size:

    public void showDialog() { FragmentManager fragmentManager = getSupportFragmentManager(); CustomDialogFragment newFragment = new CustomDialogFragment(); - + if (mIsLargeLayout) { // The device is using a large layout, so show the fragment as a dialog newFragment.show(fragmentManager, "dialog"); @@ -781,7 +781,7 @@ android.support.v4.app.DialogFragment#onDismiss onDismiss()} method in your {@li android.support.v4.app.DialogFragment}.

    You can also cancel a dialog. This is a special event that indicates the user -explicitly left the dialog without completing the task. This occurs if the user presses the +explicitly left the dialog without completing the task. This occurs if the user presses the Back button, touches the screen outside the dialog area, or if you explicitly call {@link android.app.Dialog#cancel()} on the {@link android.app.Dialog} (such as in response to a "Cancel" button in the dialog).

    diff --git a/docs/html/guide/topics/ui/drag-drop.jd b/docs/html/guide/topics/ui/drag-drop.jd index 4eb54f2325682..8871c87f4f258 100644 --- a/docs/html/guide/topics/ui/drag-drop.jd +++ b/docs/html/guide/topics/ui/drag-drop.jd @@ -978,7 +978,7 @@ protected class myDragEventListener implements View.OnDragListener { Log.e("DragDrop Example","Unknown action type received by OnDragListener."); break; } - + return false; } }; diff --git a/docs/html/guide/topics/ui/how-android-draws.jd b/docs/html/guide/topics/ui/how-android-draws.jd index 168f77b265cfa..79563692d493b 100644 --- a/docs/html/guide/topics/ui/how-android-draws.jd +++ b/docs/html/guide/topics/ui/how-android-draws.jd @@ -4,18 +4,18 @@ parent.link=index.html @jd:body -

    When an {@link android.app.Activity} receives focus, it will be requested to +

    When an {@link android.app.Activity} receives focus, it will be requested to draw its layout. -The Android framework will handle the procedure for drawing, but the +The Android framework will handle the procedure for drawing, but the {@link android.app.Activity} must provide the root node of its layout hierarchy.

    -

    Drawing begins with the root node of the layout. It is requested to measure and -draw the layout tree. Drawing is handled by walking the tree and rendering each -{@link android.view.View} that intersects the invalid region. In turn, each +

    Drawing begins with the root node of the layout. It is requested to measure and +draw the layout tree. Drawing is handled by walking the tree and rendering each +{@link android.view.View} that intersects the invalid region. In turn, each {@link android.view.ViewGroup} is responsible for requesting -each of its children to be drawn -(with the {@link android.view.View#draw(Canvas) draw()} method) +each of its children to be drawn +(with the {@link android.view.View#draw(Canvas) draw()} method) and each {@link android.view.View} is responsible for drawing itself. Because the tree is traversed in-order, this means that parents will be drawn before (i.e., behind) their children, with @@ -24,55 +24,55 @@ and each {@link android.view.View} is responsible for drawing itself.

    - Drawing the layout is a two pass process: a measure pass and a layout pass. -The measuring pass is implemented in {@link android.view.View#measure(int, int)} -and is a top-down traversal of the {@link android.view.View} tree. Each {@link android.view.View} + Drawing the layout is a two pass process: a measure pass and a layout pass. +The measuring pass is implemented in {@link android.view.View#measure(int, int)} +and is a top-down traversal of the {@link android.view.View} tree. Each {@link android.view.View} pushes dimension specifications down the tree - during the recursion. At the end of the measure pass, every + during the recursion. At the end of the measure pass, every {@link android.view.View} has stored its measurements. The second pass happens in {@link android.view.View#layout(int,int,int,int)} and is also top-down. During this pass each parent is responsible for positioning all of its children using the sizes computed in the measure pass.

    - +

    - When a {@link android.view.View} object's -{@link android.view.View#measure(int, int) measure()} method + When a {@link android.view.View} object's +{@link android.view.View#measure(int, int) measure()} method returns, its {@link android.view.View#getMeasuredWidth()} and - {@link android.view.View#getMeasuredHeight()} values must be set, along - with those for all of that {@link android.view.View} object's descendants. -A {@link android.view.View} object's measured width and -measured height values must respect the constraints imposed by the + {@link android.view.View#getMeasuredHeight()} values must be set, along + with those for all of that {@link android.view.View} object's descendants. +A {@link android.view.View} object's measured width and +measured height values must respect the constraints imposed by the {@link android.view.View} object's parents. This guarantees that at the end of the measure pass, all parents accept all of their - children's measurements. A parent {@link android.view.View} may call + children's measurements. A parent {@link android.view.View} may call {@link android.view.View#measure(int, int) measure()} more than once on its children. For example, the parent may measure each child once with unspecified dimensions to find out how big they want to be, then call - {@link android.view.View#measure(int, int) measure()} on them again with + {@link android.view.View#measure(int, int) measure()} on them again with actual numbers if the sum of all the children's - unconstrained sizes is too big or too small (that is, if the children + unconstrained sizes is too big or too small (that is, if the children don't agree among themselves - as to how much space they each get, the parent will intervene and set + as to how much space they each get, the parent will intervene and set the rules on the second pass).

    - +

    Depending on the layout that your application is currently showing, the UI flow may be different. For example, if your application is in the dual-pane @@ -66,7 +66,7 @@ public class NewsReaderActivity extends FragmentActivity { setContentView(R.layout.main_layout); View articleView = findViewById(R.id.article); - mIsDualPane = articleView != null && + mIsDualPane = articleView != null && articleView.getVisibility() == View.VISIBLE; } } @@ -139,7 +139,7 @@ public void onCreate(Bundle savedInstanceState) { else { /* use list navigation (spinner) */ actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST); - SpinnerAdapter adap = new ArrayAdapter(this, + SpinnerAdapter adap = new ArrayAdapter(this, R.layout.headline_item, CATEGORIES); actionBar.setListNavigationCallbacks(adap, handler); } @@ -157,7 +157,7 @@ large screens, but is a separate activity on smaller screens.

    In cases like this, you can usually avoid code duplication by reusing the same {@link android.app.Fragment} subclass in several activities. For example, -ArticleFragment +ArticleFragment is used in the dual-pane layout:

    {@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} @@ -206,7 +206,7 @@ activity (as opposed to notifying a specific hard-coded activity):

    public class HeadlinesFragment extends ListFragment { ... @Override - public void onItemClick(AdapterView<?> parent, + public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (null != mHeadlineSelectedListener) { mHeadlineSelectedListener.onHeadlineSelected(position); diff --git a/docs/html/training/multiscreen/index.jd b/docs/html/training/multiscreen/index.jd index 8eff246cd8ebc..2c59facbda771 100644 --- a/docs/html/training/multiscreen/index.jd +++ b/docs/html/training/multiscreen/index.jd @@ -7,10 +7,10 @@ startpage=true @jd:body -
    -
    - -

    Dependencies and prerequisites

    +
    +
    + +

    Dependencies and prerequisites

    - +

    NewsReader.zip

    +
    + +
    +
    +

    Android powers hundreds of device types with several different screen sizes, ranging from small phones to large TV sets. Therefore, it’s important that you design your application to be compatible with all screen sizes so it’s available to as many @@ -62,26 +62,26 @@ of reusable code for your own application.

    href="{@docRoot}tools/support-library/index.html">support library in order to use the {@link android.app.Fragment} APIs on versions lower than Android 3.0. You must download and add the library to your application in order to use all APIs in this class.

    - -

    Lessons

    - -
    -
    Supporting Different Screen Sizes
    + +

    Lessons

    + +
    +
    Supporting Different Screen Sizes
    This lesson walks you through how to design layouts that adapts several different screen sizes (using flexible dimensions for views, {@link android.widget.RelativeLayout}, screen size and orientation qualifiers, - alias filters, and nine-patch bitmaps).
    - + alias filters, and nine-patch bitmaps). +
    Supporting Different Screen - Densities
    + Densities
    This lesson shows you how to support screens that have different pixel densities (using density-independent pixels and providing - bitmaps appropriate for each density).
    - -
    Implementing Adaptative UI Flows
    + bitmaps appropriate for each density). + +
    Implementing Adaptative UI Flows
    This lesson shows you how to implement your UI flow in a way that adapts to several screen size/density combinations (run-time detection of active layout, reacting according to - current layout, handling screen configuration changes).
    -
    + current layout, handling screen configuration changes). +
    diff --git a/docs/html/training/multiscreen/screensizes.jd b/docs/html/training/multiscreen/screensizes.jd index 2cd59ee90a564..040bb85a88e0c 100755 --- a/docs/html/training/multiscreen/screensizes.jd +++ b/docs/html/training/multiscreen/screensizes.jd @@ -10,8 +10,8 @@ next.link=screendensities.html -
    -
    +
    +

    This lesson teaches you to

      @@ -30,27 +30,27 @@ next.link=screendensities.html
    1. Supporting Multiple Screens
    2. -

      Try it out

      - -
      +

      Try it out

      + +
      Download the sample app -

      NewsReader.zip

      -
      - -
      -
    +

    NewsReader.zip

    +
    + +
    +

    This lesson shows you how to support different screen sizes by:

    -
      -
    • Ensuring your layout can be adequately resized to fit the screen
    • -
    • Providing appropriate UI layout according to screen configuration
    • +
        +
      • Ensuring your layout can be adequately resized to fit the screen
      • +
      • Providing appropriate UI layout according to screen configuration
      • Ensuring the correct layout is applied to the correct screen
      • -
      • Providing bitmaps that scale correctly
      • -
      +
    • Providing bitmaps that scale correctly
    • +
    -

    Use "wrap_content" and "match_parent"

    +

    Use "wrap_content" and "match_parent"

    To ensure that your layout is flexible and adapts to different screen sizes, you should use "wrap_content" and "match_parent" for the width @@ -78,11 +78,11 @@ width and height:

    and landscape (right).

    -

    Use RelativeLayout

    +

    Use RelativeLayout

    You can construct fairly complex layouts using nested instances of {@link android.widget.LinearLayout} and -combinations of "wrap_content" and "match_parent" sizes. +combinations of "wrap_content" and "match_parent" sizes. However, {@link android.widget.LinearLayout} does not allow you to precisely control the spacial relationships of child views; views in a {@link android.widget.LinearLayout} simply line up side-by-side. If you need child views to be oriented in variations other than a straight line, a @@ -139,8 +139,8 @@ the right side of the screen.

    spatial relationships are preserved as specified by the {@link android.widget.RelativeLayout.LayoutParams}.

    - -

    Use Size Qualifiers

    + +

    Use Size Qualifiers

    There's only so much mileage you can get from a flexible layout or relative layout like the one in the previous sections. While those layouts adapt to @@ -148,7 +148,7 @@ different screens by stretching the space within and around components, they may not provide the best user experience for each screen size. Therefore, your application should not only implement flexible layouts, but should also provide several alternative layouts to target different screen configurations. You do -so by using configuration qualifiers, which allows the runtime +so by using configuration qualifiers, which allows the runtime to automatically select the appropriate resource based on the current device’s configuration (such as a different layout design for different screen sizes).

    @@ -209,13 +209,13 @@ layout.

    However, this won't work well on pre-3.2 devices, because they don't recognize sw600dp as a size qualifier, so you still have to use the large -qualifier as well. So, you should have a file named +qualifier as well. So, you should have a file named res/layout-large/main.xml which is identical to res/layout-sw600dp/main.xml. In the next section you'll see a technique that allows you to avoid duplicating the layout files this way.

    -

    Use Layout Aliases

    +

    Use Layout Aliases

    The smallest-width qualifier is available only on Android 3.2 and above. Therefore, you should also still use the abstract size bins (small, normal, @@ -271,7 +271,7 @@ applied to tablets and TVs regardless of Android version (pre-3.2 tablets and TV {@code large}, and post-3.2 will match sw600dp).

    -

    Use Orientation Qualifiers

    +

    Use Orientation Qualifiers

    Some layouts work well in both landscape and portrait orientations, but most of them can benefit from adjustments. In the News Reader sample app, here is how the layout @@ -287,7 +287,7 @@ behaves in each screen size and orientation:

  • TV, landscape: dual pane, wide, with action bar
  • -

    So each of these layouts is defined in an XML file in the +

    So each of these layouts is defined in an XML file in the res/layout/ directory. To then assign each layout to the various screen configurations, the app uses layout aliases to match them to each configuration:

    @@ -361,7 +361,7 @@ borders indicate the places where the image can be stretched, and the ones on the right and bottom borders indicate where the content should be placed.

    -

    Also, notice the .9.png extension. You must use this +

    Also, notice the .9.png extension. You must use this extension, since this is how the framework detects that this is a nine-patch image, as opposed to a regular PNG image.

    diff --git a/docs/html/training/notify-user/build-notification.jd b/docs/html/training/notify-user/build-notification.jd index d24a4960a9872..2f96a20985edf 100644 --- a/docs/html/training/notify-user/build-notification.jd +++ b/docs/html/training/notify-user/build-notification.jd @@ -42,9 +42,9 @@ trainingnavtop=true

    This lesson explains how to create and issue a notification.

    -

    The examples in this class are based on the -{@link android.support.v4.app.NotificationCompat.Builder} class. -{@link android.support.v4.app.NotificationCompat.Builder} +

    The examples in this class are based on the +{@link android.support.v4.app.NotificationCompat.Builder} class. +{@link android.support.v4.app.NotificationCompat.Builder} is in the Support Library. You should use {@link android.support.v4.app.NotificationCompat} and its subclasses, particularly {@link android.support.v4.app.NotificationCompat.Builder}, to @@ -52,9 +52,9 @@ provide the best notification support for a wide range of platforms.

    Create a Notification Builder

    -

    When creating a notification, specify the UI content and actions with a -{@link android.support.v4.app.NotificationCompat.Builder} object. At bare minimum, -a {@link android.support.v4.app.NotificationCompat.Builder Builder} +

    When creating a notification, specify the UI content and actions with a +{@link android.support.v4.app.NotificationCompat.Builder} object. At bare minimum, +a {@link android.support.v4.app.NotificationCompat.Builder Builder} object must include the following:

      @@ -96,7 +96,7 @@ of {@link android.app.Activity} you're starting. When you start an {@link android.app.Activity} from a notification, you must preserve the user's expected navigation experience. In the snippet below, clicking the notification opens a new activity that effectively extends the behavior of the notification. In this -case there is no need to create an artificial back stack (see +case there is no need to create an artificial back stack (see Preserving Navigation when Starting an Activity for more information):

      @@ -132,11 +132,11 @@ mBuilder.setContentIntent(resultPendingIntent);

    To issue the notification:

      -
    • Get an instance of {@link android.app.NotificationManager}.
    • +
    • Get an instance of {@link android.app.NotificationManager}.
    • Use the {@link android.app.NotificationManager#notify notify()} method to issue the -notification. When you call {@link android.app.NotificationManager#notify notify()}, specify a notification ID. -You can use this ID to update the notification later on. This is described in more detail in +notification. When you call {@link android.app.NotificationManager#notify notify()}, specify a notification ID. +You can use this ID to update the notification later on. This is described in more detail in Managing Notifications.
    • Call {@link @@ -152,7 +152,7 @@ NotificationCompat.Builder mBuilder; // Sets an ID for the notification int mNotificationId = 001; // Gets an instance of the NotificationManager service -NotificationManager mNotifyMgr = +NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Builds the notification and issues it. mNotifyMgr.notify(mNotificationId, mBuilder.build()); diff --git a/docs/html/training/notify-user/display-progress.jd b/docs/html/training/notify-user/display-progress.jd index 3439571fe3064..e2cf033d7b6c2 100644 --- a/docs/html/training/notify-user/display-progress.jd +++ b/docs/html/training/notify-user/display-progress.jd @@ -59,9 +59,9 @@ trainingnavtop=true

      Display a Fixed-duration Progress Indicator

      To display a determinate progress bar, add the bar to your notification by calling - {@link android.support.v4.app.NotificationCompat.Builder#setProgress - setProgress(max, progress, false)} and then issue the notification. - The third argument is a boolean that indicates whether the + {@link android.support.v4.app.NotificationCompat.Builder#setProgress + setProgress(max, progress, false)} and then issue the notification. + The third argument is a boolean that indicates whether the progress bar is indeterminate (true) or determinate (false). As your operation proceeds, increment progress, and update the notification. At the end of the operation, @@ -74,7 +74,7 @@ trainingnavtop=true You can either leave the progress bar showing when the operation is done, or remove it. In either case, remember to update the notification text to show that the operation is complete. To remove the progress bar, call - {@link android.support.v4.app.NotificationCompat.Builder#setProgress + {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress(0, 0, false)}. For example:

      @@ -136,14 +136,14 @@ new Thread(
       

      To display a continuing (indeterminate) activity indicator, add it to your notification with {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress(0, 0, true)} - and issue the notification. The first two arguments are ignored, and the third argument + and issue the notification. The first two arguments are ignored, and the third argument declares that the indicator is indeterminate. The result is an indicator that has the same style as a progress bar, except that its animation is ongoing.

      Issue the notification at the beginning of the operation. The animation will run until you modify your notification. When the operation is done, call - {@link android.support.v4.app.NotificationCompat.Builder#setProgress + {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress(0, 0, false)} and then update the notification to remove the activity indicator. Always do this; otherwise, the animation will run even when the operation is complete. Also remember to change the notification text to indicate that the operation is complete. @@ -160,7 +160,7 @@ mNotifyManager.notify(id, mBuilder.build());

      Replace the lines you've found with the following lines. Notice that the third parameter - in the {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress()} + in the {@link android.support.v4.app.NotificationCompat.Builder#setProgress setProgress()} call is set to {@code true} to indicate that the progress bar is indeterminate:

      diff --git a/docs/html/training/notify-user/expanded.jd b/docs/html/training/notify-user/expanded.jd index b657426829565..23d85d4380928 100644 --- a/docs/html/training/notify-user/expanded.jd +++ b/docs/html/training/notify-user/expanded.jd @@ -75,7 +75,7 @@ big view give users access to same functionality:

    The normal view provides these features through a new activity that launches -when the user clicks the notification. Keep this in mind as you design your notifications—first +when the user clicks the notification. Keep this in mind as you design your notifications—first provide the functionality in the normal view, since this is how many users will interact with the notification.

    @@ -87,19 +87,19 @@ to construct and issue the notification.

    In this snippet, the {@link android.app.IntentService} method -{@link android.app.IntentService#onHandleIntent onHandleIntent()} specifies the new activity +{@link android.app.IntentService#onHandleIntent onHandleIntent()} specifies the new activity that will be launched if the user -clicks the notification itself. The method -{@link android.support.v4.app.NotificationCompat.Builder#setContentIntent setContentIntent()} +clicks the notification itself. The method +{@link android.support.v4.app.NotificationCompat.Builder#setContentIntent setContentIntent()} defines a pending intent that should be fired when the user clicks the notification, thereby launching the activity.

    Intent resultIntent = new Intent(this, ResultActivity.class);
     resultIntent.putExtra(CommonConstants.EXTRA_MESSAGE, msg);
    -resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
    +resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
             Intent.FLAG_ACTIVITY_CLEAR_TASK);
    -     
    -// Because clicking the notification launches a new ("special") activity, 
    +
    +// Because clicking the notification launches a new ("special") activity,
     // there's no need to create an artificial back stack.
     PendingIntent resultPendingIntent =
              PendingIntent.getActivity(
    @@ -130,8 +130,8 @@ snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
     PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
     
    -

    This snippet shows how to construct the -{@link android.support.v4.app.NotificationCompat.Builder Builder} object. +

    This snippet shows how to construct the +{@link android.support.v4.app.NotificationCompat.Builder Builder} object. It sets the style for the big view to be "big text," and sets its content to be the reminder message. It uses {@link android.support.v4.app.NotificationCompat.Builder#addAction addAction()} diff --git a/docs/html/training/notify-user/index.jd b/docs/html/training/notify-user/index.jd index 616e767873f8e..57efd65128497 100644 --- a/docs/html/training/notify-user/index.jd +++ b/docs/html/training/notify-user/index.jd @@ -43,9 +43,9 @@ class="button">Download the sample

    - A notification is a user interface element that you display outside your app's normal UI to indicate - that an event has occurred. Users can choose to view the notification while using other apps and respond - to it when it's convenient for them. + A notification is a user interface element that you display outside your app's normal UI to indicate + that an event has occurred. Users can choose to view the notification while using other apps and respond + to it when it's convenient for them.

    @@ -86,10 +86,10 @@ class="button">Download the sample
    - Learn how to create a big view within an expanded notification, while still maintaining + Learn how to create a big view within an expanded notification, while still maintaining backward compatibility.
    - +
    Displaying Progress in a Notification diff --git a/docs/html/training/notify-user/navigation.jd b/docs/html/training/notify-user/navigation.jd index b7051ab5f1fab..cdb7f3d6e0c45 100644 --- a/docs/html/training/notify-user/navigation.jd +++ b/docs/html/training/notify-user/navigation.jd @@ -37,7 +37,7 @@ trainingnavtop=true

    - Part of designing a notification is preserving the user's expected navigation experience. + Part of designing a notification is preserving the user's expected navigation experience. For a detailed discussion of this topic, see the Notifications API guide. @@ -49,7 +49,7 @@ trainingnavtop=true

    You're starting an {@link android.app.Activity} that's part of the application's normal - workflow. + workflow.
    Special activity @@ -202,7 +202,7 @@ NotificationCompat.Builder builder = new NotificationCompat.Builder(this); Intent notifyIntent = new Intent(new ComponentName(this, ResultActivity.class)); // Sets the Activity to start in a new, empty task -notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | +notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // Creates the PendingIntent PendingIntent notifyIntent = diff --git a/docs/html/training/run-background-service/report-status.jd b/docs/html/training/run-background-service/report-status.jd index 41121c17e3e68..41fbb00e115ff 100644 --- a/docs/html/training/run-background-service/report-status.jd +++ b/docs/html/training/run-background-service/report-status.jd @@ -91,7 +91,7 @@ public class RSSPullService extends IntentService {

    Receive Status Broadcasts from an IntentService

    - + To receive broadcast {@link android.content.Intent} objects, use a subclass of {@link android.content.BroadcastReceiver}. In the subclass, implement the {@link android.content.BroadcastReceiver#onReceive BroadcastReceiver.onReceive()} callback @@ -137,7 +137,7 @@ public class DisplayActivity extends FragmentActivity { // The filter's action is BROADCAST_ACTION IntentFilter mStatusIntentFilter = new IntentFilter( Constants.BROADCAST_ACTION); - + // Adds a data filter for the HTTP scheme mStatusIntentFilter.addDataScheme("http"); ... @@ -194,6 +194,6 @@ public class DisplayActivity extends FragmentActivity { {@link android.content.Intent}.

    - +

    diff --git a/docs/html/training/sign-in/index.jd b/docs/html/training/sign-in/index.jd index d7c8e1d397ab6..a5859441d64fd 100644 --- a/docs/html/training/sign-in/index.jd +++ b/docs/html/training/sign-in/index.jd @@ -11,8 +11,8 @@ page.trainingcourse=true alt="Google maps sample image">

    - Google Sign-In for Android lets you authenticate a user with the same credentials they use on - Google. After a user signs in with Google, you can create more engaging experiences and drive + Google Sign-In for Android lets you authenticate a user with the same credentials they use on + Google. After a user signs in with Google, you can create more engaging experiences and drive usage of your app.

    @@ -34,8 +34,8 @@ page.trainingcourse=true

    Access the profile and social graph

    - After users have signed in with Google, your app can welcome them by name and display their - picture. If your app requests social scopes, it can connect users with friends, and access + After users have signed in with Google, your app can welcome them by name and display their + picture. If your app requests social scopes, it can connect users with friends, and access age range, language, and public profile information.
    Getting Profile Information. @@ -47,6 +47,6 @@ page.trainingcourse=true The Google Android APIs are part of the Google Play services platform. To use Google features, set up the Google Play services SDK in your app development project. For more information, see the Start Integrating + "https://developers.google.com/identity/sign-in/android/start-integrating">Start Integrating guide for Google Sign-In.

    \ No newline at end of file diff --git a/docs/html/wear/preview/features/ime.jd b/docs/html/wear/preview/features/ime.jd index 1301be9afb2a7..b07736f1da30e 100644 --- a/docs/html/wear/preview/features/ime.jd +++ b/docs/html/wear/preview/features/ime.jd @@ -19,14 +19,14 @@ page.tags="wear" -

    Wear 2.0 supports input methods beyond voice by extending the Android +

    Wear 2.0 supports input methods beyond voice by extending the Android Input Method Framework (IMF) to Android Wear. IMF allows for virtual, on-screen - keyboards and other input methods to be used for text entry. The IMF APIs used - for Wear devices are the same as other form factors, though usage is slightly + keyboards and other input methods to be used for text entry. The IMF APIs used + for Wear devices are the same as other form factors, though usage is slightly different due to limited screen real estate.

    -

    Wear 2.0 comes with the system default Input Method Editor (IME) -and opens up the IMF APIs for third-party developers to create custom input +

    Wear 2.0 comes with the system default Input Method Editor (IME) +and opens up the IMF APIs for third-party developers to create custom input methods for Wear.

    @@ -46,17 +46,17 @@ documentation for

    Invoking an Input Method

    -If you are developing an IME for Wear, remember that the -feature is supported only on Android 6.0 (API level 23) and higher versions of -the platform. -To ensure that your IME can only be installed on Wearables that support input +If you are developing an IME for Wear, remember that the +feature is supported only on Android 6.0 (API level 23) and higher versions of +the platform. +To ensure that your IME can only be installed on Wearables that support input methods beyond voice, add the following to your app's manifest:
     <uses-sdk android:minSdkVersion="23" />
     
    -This indicates that your app requires Android 6.0 or higher. +This indicates that your app requires Android 6.0 or higher. For more information, see API Levels - and the documentation for the <uses-sdk> + and the documentation for the <uses-sdk> element.

    To control how your app is filtered from devices that do not support Wear @@ -67,14 +67,14 @@ IMEs (for example, on Phone), add the following to your app's manifest:

    Wear provides user settings on the watch that lets the user to enable multiple - IMEs from the list of installed IMEs. Once the users enable your IME, they + IMEs from the list of installed IMEs. Once the users enable your IME, they can invoke your IME from:

      -
    • A notification or an app using the +
    • A notification or an app using the RemoteInput API.
    • -
    • Wear apps with an +
    • Wear apps with an EditText - field. Touching a text field places the cursor in the field and automatically + field. Touching a text field places the cursor in the field and automatically displays the IME on focus.
    @@ -86,10 +86,10 @@ IMEs (for example, on Phone), add the following to your app's manifest:
    • Set Default Action

      -{@code RemoteInput} +{@code RemoteInput} and Wear apps expect only single-line text entry. The ENTER key should always trigger a call to sendDefaultEditorAction, - which causes the app to dismiss the keyboard and continue on to the next step + which causes the app to dismiss the keyboard and continue on to the next step or action.

    • @@ -97,22 +97,22 @@ and Wear apps expect only single-line text entry. The ENTER key should always tr

      Input methods on Wear consume most of the screen, leaving very little of the app visible; using full-screen mode ensures an optimal user experience regardless - of the app UI. In full-screen mode, an + of the app UI. In full-screen mode, an {@code ExtractEditText} provides a mirrored view of the text field being edited and can be styled to blend with the rest of - the input method UI. For more details on full-screen mode, see + the input method UI. For more details on full-screen mode, see InputMethodService.

    • Handle InputType flags

      -For privacy reasons, at a minimum you should handle the {@code InputType} -flag {@code TYPE_TEXT_VARIATION_PASSWORD} in your IME. When your IME is in -password mode, make sure that your keyboard is optimized for single key press -(auto spelling correction, auto completion and gesture input are disabled). -Most importantly, keyboard in password mode should support ASCII symbols -regardless of the input language. For more details, see +For privacy reasons, at a minimum you should handle the {@code InputType} +flag {@code TYPE_TEXT_VARIATION_PASSWORD} in your IME. When your IME is in +password mode, make sure that your keyboard is optimized for single key press +(auto spelling correction, auto completion and gesture input are disabled). +Most importantly, keyboard in password mode should support ASCII symbols +regardless of the input language. For more details, see Specifying The Input Method Type.

    • @@ -120,9 +120,9 @@ regardless of the input language. For more details, see
    • Provide a key for switching to the next input method

      Android allows users to easily switch between all IMEs supported by the platform. - In your IME implementation, set the boolean + In your IME implementation, set the boolean supportsSwitchingToNextInputMethod = true - to enable your IME to support the switching mechanism + to enable your IME to support the switching mechanism (so that apps can switch to the next platform-supported IME).

    • diff --git a/docs/html/wear/preview/features/notifications.jd b/docs/html/wear/preview/features/notifications.jd index c84a47002f9d1..dcc09709deb3f 100644 --- a/docs/html/wear/preview/features/notifications.jd +++ b/docs/html/wear/preview/features/notifications.jd @@ -155,7 +155,7 @@ action in the notification unless a different action is specified using

      If you have a chat messaging app, your notifications should use {@code Notification.MessagingStyle}, which is new in Android N. Wear 2.0 uses the chat messages included - in a {@code MessagingStyle} notification + in a {@code MessagingStyle} notification (see {@code addMessage()}) to provide a rich chat app-like experience in the expanded notification. @@ -195,7 +195,7 @@ following:

    • Use {@code Notification.MessagingStyle}.
    • Call the method {@code setAllowGeneratedReplies()} for the notification action. - For more information, see the downloadable + For more information, see the downloadable API reference.
    • Ensure that the notification action has a diff --git a/docs/html/work/cosu.jd b/docs/html/work/cosu.jd index 8bc54d49bc8ec..f66006bab1f5d 100644 --- a/docs/html/work/cosu.jd +++ b/docs/html/work/cosu.jd @@ -223,7 +223,7 @@ and {@link android.app.Activity#onPause()}

    -Starting from Marshmallow, if your app is whitelisted by an EMM using {@link +Starting from Marshmallow, if your app is whitelisted by an EMM using {@link android.app.admin.DevicePolicyManager#setLockTaskPackages setLockTaskPackages}, your activities can automatically start lock task mode when the app is launched. @@ -253,15 +253,15 @@ launch into lock task mode. Non-privileged apps are treated as normal.

  • The default value of the {@link android.R.attr#lockTaskMode} attribute is -normal. When this attribute is set to normal, tasks don’t launch into -{@link android.R.attr#lockTaskMode}, unless {@link android.app.Activity#startLockTask()} +normal. When this attribute is set to normal, tasks don’t launch into +{@link android.R.attr#lockTaskMode}, unless {@link android.app.Activity#startLockTask()} is called. To call {@link android.app.Activity#startLockTask()}, -applications still need to be whitelisted using -{@link android.app.admin.DevicePolicyManager#setLockTaskPackages setLockTaskPackages}, +applications still need to be whitelisted using +{@link android.app.admin.DevicePolicyManager#setLockTaskPackages setLockTaskPackages}, otherwise, the user sees a dialog to approve entering pinned mode.
  • - +

    To have your activity automatically enter {@link android.R.attr#lockTaskMode}, change the value of this attribute to if_whitelisted. Doing so causes your app to behave in this manner: @@ -289,7 +289,7 @@ Example XML as follows:

    Given either of these options, you still need to create a mechanism for calling {@link android.app.Activity#stopLockTask()} so that users can -exit {@link android.R.attr#lockTaskMode}. +exit {@link android.R.attr#lockTaskMode}.

    @@ -298,7 +298,7 @@ exit {@link android.R.attr#lockTaskMode}.

    To manage applications in COSU, you need a DPC running as device -owner to set several policies on the device. +owner to set several policies on the device.

    diff --git a/docs/html/work/device-management-policy.jd b/docs/html/work/device-management-policy.jd index d564b8969512f..fd0915083c705 100644 --- a/docs/html/work/device-management-policy.jd +++ b/docs/html/work/device-management-policy.jd @@ -14,7 +14,7 @@ parent.link=index.html

  • Activate the Device Administrator
  • Implement the Device Policy Controller
  • - +

    You should also read