App Widgets

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 to as Widgets in the user interface, and you can publish one with an App Widget provider. An application component that is able to hold other App Widgets is called an App Widget host. The screenshot below shows the Music App Widget.

App 위젯들은 (홈 스크린과 같은) 다른 애플리케이션 내에 임베디드될 수 있는 축소된 애플리케이션 뷰이며, 주기적인 업데이트를 수신한다. 이러한 뷰들은 사용자 인터페이스에서 위젯Widget으로써 불려진다. 그리고 여러분은 App 위젯 프로바이더를 사용해서 그것을 배포할 수 있다. 다른 App 위젯을 보유할 수 있는 애플리케이션 컴포넌트는 App 위젯 호스트라고 불리운다. 아래의 스크린 샷은 뮤직 App 위젯을 보여준다.

This document describes how to publish an App Widget using an App Widget provider.

이 문서는 App 위젯 프로바이더를 사용하여 App 위젯을 배포하는 방식을 설명한다.

The Basics

To create an App Widget, you need the following:

App 위젯을 생성하기 위해서는, 여러분은 다음과 같은 것을 필요로 한다.

AppWidgetProviderInfo object
Describes the metadata for an App Widget, such as the App Widget's layout, update frequency, and the AppWidgetProvider class. This should be defined in XML.
AppWidgetProvider class implementation
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, enabled, disabled and deleted.
View layout
Defines the initial layout for the App Widget, defined in XML.
AppWidgetProviderInfo 오브젝트
App 위젯의 레이아웃, 업데이트 빈도, 그리고 AppWidgetProvider 클래스와 같은 App 위젯에 대한 메타 데이터를 기술한다. 이것은 XML로 정의되어야 한다.
AppWidgetProvider 클래스 구현
여러분이 브로드캐스트 이벤트에 기초해서 프로그램적으로 App 위젯과 인터페이스하는 것을 가능하게 하는 기본적인 메쏘드를 정의한다. 그것을 통해, 여러분은 App 위젯이 업데이트되고, 활성화되고, 비활성화되고, 그리고 삭제될 때 브로드캐스트를 수신할 것이다.
뷰(View) 레이아웃
XML로 정의된 App 위젯에 대한 초기 레이아웃을 정의한다.

Additionally, you can implement an App Widget configuration Activity. This is an optional Activity that launches when the user adds your App Widget and allows him or her to modify App Widget settings at create-time.

추가적으로, 여러분은 App 위젯 설정configuration 액티비티를 구현할 수 있다. 이 액티비티는 선택사항이며, 그것은 사용자가 여러분의 App 위젯을 추가할 때 실행되며, 그것은 사용자가 생성 시점에서 App 위젯 설정을 수정하는 것을 가능하게 한다.

The following sections describe how to setup each of these components.

아래의 섹션들은 각각의 이러한 컴포넌트들을 구성하는 방법을 설명한다.

Declaring an App Widget in the Manifest

First, declare the AppWidgetProvider class in your application's AndroidManifest.xml file. For example:

먼저, 여러분의 애플리케이션의 AndroidManifest.xml 파일에 AppWidgetProvider를 선언하라. 예를 들어 다음과 같다.

<receiver android:name="ExampleAppWidgetProvider" >
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>
    <meta-data android:name="android.appwidget.provider"
               android:resource="@xml/example_appwidget_info" />
</receiver>

The <receiver> element requires the android:name attribute, which specifies the AppWidgetProvider used by the App Widget.

<receiver> 엘리먼트는 App 위젯에 의해 사용되는 AppWidgetProvider를 명시하는 android:name 애트리뷰트를 요구한다.

The <intent-filter> element must include an <action> element with the android:name attribute. This attribute specifies that the AppWidgetProvider accepts the ACTION_APPWIDGET_UPDATE broadcast. This is the only broadcast that you must explicitly declare. The AppWidgetManager automatically sends all other App Widget broadcasts to the AppWidgetProvider as necessary.

<intent-filter> 엘리먼트는 android:name 애트리뷰트를 가지는 <action> 엘리먼트를 포함해야 한다. 이 애트리뷰트는 AppWidgetProvider가 ACTION_APPWIDGET_UPDATE 브로드캐스트를 받는다는 것을 지정해야 한다. 이 브로드캐스트는 여러분이 명시적으로 선언해야 하는 유일한 브로드캐스트이다. AppWidgetManager는 필요에 따라 모든 다른 App 위젯 브로드캐스트들을 AppWidgetProvider에게 자동으로 전송한다.

The <meta-data> element specifies the AppWidgetProviderInfo resource and requires the following attributes:

<meta-data> 엘리먼트는 AppWidgetProviderInfo 리소스를 지정하며, 다음과 같은 애트리뷰트들을 요구한다.

  • android:name - Specifies the metadata name. Use android.appwidget.provider to identify the data as the AppWidgetProviderInfo descriptor.
  • android:resource - Specifies the AppWidgetProviderInfo resource location.
  • android:name - 데이터 이름을 지정한다. AppWidgetProviderInfo 기술자(descriptor)로써, 데이터를 식별하기 위해 android.appwidget.provider를 사용하라.
  • android:resource - AppWidgetProviderInfo 리소스 위치를 지정한다.

Adding the AppWidgetProviderInfo Metadata

The 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/ folder.

AppWidgetProviderInfo는 App 위젯의 필수적인 특질quality을 정의한다. 그것의 최소 레이아웃 크기, 그것의 초기 레이아웃 리소스, 얼마나 자주 App 위젯을 업데이트 하는지, 그리고 (선택 사항으로) 생성시점에서 실행할 설정configuration 액티비티와 같은 것들이 그것이다. 하나의 <appwidget-provider> 엘리먼트를 사용해서 XML 리소스에 AppWidgetProviderInfo를 정의하라. 그리고 그것을 프로젝트의 res/xml/ 폴더에 저장하라.

For example:

예를 들어 다음과 같다.

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="86400000"
    android:initialLayout="@layout/example_appwidget"
    android:configure="com.example.android.ExampleAppWidgetConfigure" >
</appwidget-provider>

Here's a summary of the <appwidget-provider> attributes:

여기에 <appwidget-provider> 애트리뷰트들에 대한 요약이 있다.

  • The values for the minWidth and minHeight attributes specify the minimum area required by the App Widget's layout.

    The default Home screen positions App Widgets in its window based on a grid of cells that have a defined height and width. If the values for an App Widget's minimum width or height don't match the dimensions of the cells, then the App Widget dimensions round up to the nearest cell size. (See the App Widget Design Guidelines for more information on the Home screen cell sizes.)

    Because the Home screen's layout orientation (and thus, the cell sizes) can change, as a rule of thumb, you should assume the worst-case cell size of 74 pixels for the height and width of a cell. However, you must subtract 2 from the final dimension to account for any integer rounding errors that occur in the pixel count. To find your minimum width and height in density-independent pixels (dp), use this formula:
    (number of cells * 74) - 2
    Following this formula, you should use 72 dp for a height of one cell, 294 dp and for a width of four cells.

  • The updatePeriodMillis attribute defines how often the App Widget framework should request an update from the AppWidgetProvider by calling the onUpdate() method. The actual update is not guaranteed to occur exactly on time with this value and we suggest updating as infrequently as possibleperhaps no more than once an hour to conserve the battery. You might also allow the user to adjust the frequency in a configurationsome people might want a stock ticker to update every 15 minutes, or maybe only four times a day.

    Note: If the device is asleep when it is time for an update (as defined by updatePeriodMillis), then the device will wake up in order to perform the update. If you don't update more than once per hour, this probably won't cause significant problems for the battery life. If, however, you need to update more frequently and/or you do not need to update while the device is asleep, then you can instead perform updates based on an alarm that will not wake the device. To do so, set an alarm with an Intent that your AppWidgetProvider receives, using the AlarmManager. Set the alarm type to either ELAPSED_REALTIME or RTC, which will only deliver the alarm when the device is awake. Then set updatePeriodMillis to zero ("0").

  • The initialLayout attribute points to the layout resource that defines the App Widget layout.
  • The configure attribute defines the Activity to launch when the user adds the App Widget, in order for him or her to configure App Widget properties. This is optional (read Creating an App Widget Configuration Activity below).
  • minWidth와 minHeight 애트리뷰트 값은 App 위젯의 레이아웃에 의해 요구되는 최소 영역을 지정한다.

    디폴트 홈 스크린은 App 위젯을 정의된 높이와 너비을 가진 그리드grid 셀에 기반하는 자신의 윈도우에 배치한다. 만약 App 위젯의 최소 너비 또는 높이에 대한 값들이 셀의 크기에 맞지 않는다면, App 위젯 크기는 가장 근접한 셀 크기에 라운드 업round up된다(홈 스크린 셀 크기에 대한 더 많은 정보에 대해서는 http://developer.android.com의 App 위젯 디자인 가이드를 보라).

    홈 스크린의 레이아웃 오리엔테이션(그리고 그에 따른 셀 크기)이 변경될 수 있기 때문에, 경험적 법칙에 따를 경우, 여러분은 셀의 높이와 너비에 대해 최악의 경우의 셀 크기 74픽셀을 가정해야 한다. 하지만 여러분은 픽셀 수에서 발생하는 임의의 정수integer 라운딩rounding 오류에 대해 고려하기 위해 최종 크기에서 2를 빼야 한다. 밀도 독립적 픽셀(dp)로 여러분의 최소 너비와 높이를 구하기 위해서는 다음의 공식을 사용하라.(number of cells * 74) - 2이 공식에 따라서, 여러분은 하나의 셀의 높이로 72 dp를, 4개의 셀의 너비로는 294 dp를 사용해야 한다.

  • updatePeriodMillis 애트리뷰트는 얼마나 자주 App 위젯 프레임워크가 onUpdate() 메쏘드를 호출함으로써 AppWidgetProvider로부터 업데이트를 요청해야 하는가를 정의한다. 실제 업데이트는 이 값으로 지정된 시간에 정확하게 일어나는 것이 보장되지는 않는다. 그리고 우리는 가능한 한 드물게 업데이트할 것을 제안한다. 배터리를 절약하기 위해 한 시간에 많아야 한 번 하는 것이 좋다. 여러분은 또한 설정을 통해 빈도를 사용자가 조절할 수 있도록 허용할 수도 있다. 일부 사람들은 주식 시세 표시를 매 15분마다, 또는 하루에 오직 4번만 업데이트하길 원할 지도 모른다.

    Note: 디바이스가 (updatePeriodMills에 정의된 대로) 절전 상태라면, 그 디바이스는 업데이트를 수행하기 위해 깨어날 것이다. 만약 여러분이 한 시간에 한 번 이상 업데이트하지 않는다면, 이것은 아마 배터리 수명에 대한 심각한 문제를 야기시키지 않을 것이다. 하지만 여러분이 너무 자주 업데이트할 필요가 있고/있거나 디바이스가 절전 상태인 동안 업데이트할 필요가 없다면, 여러분은 대신 그 디바이스를 깨울 알람에 기반하여 업데이트를 수행할 수 있다. 그렇게 하기 위해서, 알람 매니저(AlarmManager)를 이용하여 여러분의 AppWidgetProvider가 수신하는 인텐트를 가지고 하나의 알람을 설정하라. 그리고 그 알람 타입을 ELAPSED_REALTIME 또는 RTC로 설정하라. 이것은 디바이스가 깨어날 때 그 알람을 전달할 것이다. 그리고 나서 updatePerioidMills를 “0”으로 설정하라.

  • initialLayout 애트리뷰트는 App 위젯 레이아웃을 정의하는 레이아웃 리소스를 가리킨다.
  • configure 애트리뷰트는 사용자가 App 위젯을 추가할 때 사용자에게 App 위젯 설정을 요청하기 위해 런치할 액티비티를 정의한다. 이것은 선택 사항이다(아래의 App 위젯 설정 액티비티 생성하기를 읽어라).

See the AppWidgetProviderInfo class for more information on the attributes accepted by the <appwidget-provider> element.

<appwidget-provider> 엘리먼트에 의해 수용되는 애트리뷰트들에 대한 더 많은 정보에 대해서는 AppWidgetProviderInfo 클래스를 보라.

Creating the App Widget Layout

You must define an initial layout for your App Widget in XML and save it in the project's res/layout/ directory. You can design your App Widget using the View objects listed below, but before you begin designing your App Widget, please read and understand the App Widget Design Guidelines.

여러분은 XML로 여러분의 App 위젯에 대한 초기 레이아웃을 정의하고, 그것을 프로젝트의 res/layout/ 디렉토리에 저장해야 한다. 여러분은 아래의 리스트된 뷰 오브젝트를 사용해서 여러분의 App 위젯을 디자인 할 수 있다. 그러나 여러분의 App 위젯 디자인을 시작하기에 앞서서 App 위젯 디자인 가이드라인을 이해하라.

Creating the App Widget layout is simple if you're familiar with Declaring Layout in XML. However, you must be aware that App Widget layouts are based on RemoteViews, which do not support every kind of layout or view widget.

App 위젯 레이아웃을 생성하는 것은, 만약 여러분이 XML로 레이아웃을 선언하는 것에 익숙하다면 간단하다. 하지만 여러분은 App 위젯 레이아웃은 리모트뷰RemoteViews에 기반한다는 것을 알아야 한다. 리모트뷰는 모든 종류의 레이아웃 또는 뷰 위젯을 지원하지 않는다.

A RemoteViews object (and, consequently, an App Widget) can support the following layout classes:

리모트뷰RemoteViews 오브젝트 (그리고, 결과적으로 하나의 App 위젯)은 다음과 같은 레이아웃 클래스를 지원할 수 있다.

  • FrameLayout
  • LinearLayout
  • RelativeLayout

And the following widget classes:

그리고 다음과 같은 위젯 클래스들을 지원한다.

  • AnalogClock
  • Button
  • Chronometer
  • ImageButton
  • ImageView
  • ProgressBar
  • TextView

Descendants of these classes are not supported.

이러한 클래스들의 자손들descendants은 지원되지 않는다.

Using the AppWidgetProvider Class

The AppWidgetProvider class extends BroadcastReceiver as a convenience class to handle the App Widget broadcasts. The AppWidgetProvider receives only the event broadcasts that are relevant to the App Widget, such as when the App Widget is updated, deleted, enabled, and disabled. When these broadcast events occur, the AppWidgetProvider receives the following method calls:

AppWidgetProvider 클래스는 App 위젯 브로드캐스트를 처리하기 위한 편리한 클래스로써 BroadcastReceiver를 확장한다. AppWidgetProvider는 App 위젯이 업데이트, 삭제, 활성화, 비활성화될 때와 같은 App 위젯과 관련된 이벤트 브로드캐스트만을 수신한다. 이러한 브로드캐스트 이벤트가 발생할 때, AppWidgetProvider는 다음과 같은 메쏘드 호출을 수신한다.

onUpdate(Context, AppWidgetManager, int[])
This is called to update the App Widget at intervals defined by the updatePeriodMillis attribute in the AppWidgetProviderInfo (see Adding the AppWidgetProviderInfo Metadata above). This method is also called when the user adds the App Widget, so it should perform the essential setup, such as define event handlers for Views and start a temporary Service, if necessary. However, if you have declared a configuration Activity, this method is not called when the user adds the App Widget, but is called for the subsequent updates. It is the responsibility of the configuration Activity to perform the first update when configuration is done. (See Creating an App Widget Configuration Activity below.)
이것은 AppWidgetProviderInfo(위의 AppWidgetProviderInfo 메타 데이터 추가하기를 보라)안의 updatePeriodMillis 애트리뷰트에 의해 정의된 간격으로 App 위젯을 업데이트하기 위해 호출된다. 이 메쏘드는 또한 사용자가 App 위젯을 추가할 때 호출된다. 그러므로 그것은 만약 필요하다면, 뷰에 대한 이벤트 핸들러를 정의하고 임시적인 서비스를 시작하는 것과 같은 필수적인 셋업을 수행해야 한다. 하지만 만약 여러분이 설정configuration 액티비티를 선언했다면, 이 메쏘드는 사용자가 App 위젯을 추가할 때 호출되지 않고, 이어지는 업데이트들에 대해서 호출된다. 설정configuration이 완료되었을 때 첫 번째 업데이트를 수행하는 것은, 설정configuration 액티비티의 책임이다(아래의 App 위젯 설정 액티비티 생성하기를 보라).
onDeleted(Context, int[])
This is called every time an App Widget is deleted from the App Widget host.
이것은 App 위젯이 App 위젯 호스트로부터 삭제될 때마다 호출된다.
onEnabled(Context)
This is called when an instance the App Widget is created for the first 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.
이것은 App 위젯 인스턴스가 최초로 생성될 때 호출된다. 예를 들어 만약 사용자가 여러분의 App 위젯에 대한 두 개의 인스턴스를 추가한다면, 이것은 오직 첫 번째만 호출된다. 만약 여러분이 새로운 데이터베이스를 오픈하거나 모든 App 위젯 인스턴스에 대해 한 번만 발생시켜야 할 필요가 있는 다른 셋업을 수행할 필요가 있다면, 이곳이 그것을 하기 좋은 위치이다.
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 onEnabled(Context), such as delete a temporary database.
이것은 App 위젯 호스트로부터 여러분의 App 위젯에 대한 마지막 인스턴스가 제거될 때 호출된다. 이곳은 여러분이 임시적인 데이터베이스를 삭제하는 것과 같은 onEnabled(Context)에서 했던 어떤 작업들을 일소clean up해야 하는 곳이다.
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 구현은 모든 App 위젯 브로드캐스트를 여과해서 적절하게 위의 메쏘드를 호출한다.

Note: In Android 1.5, there is a known issue in which the onDeleted() method will not be called when it should be. To work around this issue, you can implement onReceive() as described in this Group post to receive the onDeleted() callback.

Note: 안드로이드 1.5에서, onDelete() 메쏘드가 호출되어야 할 때 호출되지 않는 이미 알려진 이슈가 있다. 이 이슈를 회피하기 위해서, 여러분은 onDeleted() 콜백을 수신하기 위한 이 그룹 포스트에서 설명된대로 onReceive()를 구현할 수 있다.

The most important AppWidgetProvider callback is onUpdated() 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 onUpdated() 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 implementation of AppWidgetProvider:

가장 중요한 AppWidgetProvider 콜백은 onUpdated()이다. 왜냐하면, 그것은 (만약 여러분이 설정(configuration) 액티비티를 사용하지 않는 한) 각각의 App 위젯이 그것을 보유하는 것에 추가될 때마다 호출되기 때문이다. 만약 여러분의 App 위젯이 어떤 사용자와의 상호작용 이벤트를 받아들인다면, 여러분은 이 콜백에서 이벤트 핸들러를 등록할 필요가 있다. 만약 여러분의 App 위젯이 임시적인 파일 또는 데이터베이스를 생성하지 않거나, 또는 일소clean-up를 요구하는 다른 작업을 수행하지 않는다면, onUpdated()는 여러분이 정의할 필요가 있는 오직 유일한 콜백 메쏘드일 수도 있다. 예를 들어 만약 여러분이 클릭될 때 액티비티를 시작시키는 버튼을 가지고 있는 App 위젯을 원한다면, 여러분은 다음과 같은 AppWidgetProvider 구현을 사용할 수 있다.

public class ExampleAppWidgetProvider extends AppWidgetProvider {

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        // Perform this loop procedure for each App Widget that belongs to this provider
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];

            // Create an Intent to launch ExampleActivity
            Intent intent = new Intent(context, ExampleActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            // Get the layout for the App Widget and attach an on-click listener to the button
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);
            views.setOnClickPendingIntent(R.id.button, pendingIntent);

            // Tell the AppWidgetManager to perform an update on the current App Widget
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }
}

This AppWidgetProvider defines only the onUpdated() method for the purpose of defining a PendingIntent that launches an Activity and attaching it to the App Widget's button with setOnClickPendingIntent(int, PendingIntent). Notice that it includes a loop that iterates through each entry in appWidgetIds, which is an array of IDs that identify each App Widget created by this provider. In this way, if the user creates more than one instance of the App Widget, then they are all updated simultaneously. However, only one updatePeriodMillis schedule will be managed for all instances of the App Widget. For example, if the update schedule is defined to be every two hours, and a second instance of the App Widget is added one hour after the first one, then they will both be updated on the period defined by the first one and the second update period will be ignored (they'll both be updated every two hours, not every hour).

이 AppWidgetProvider는 액티비티를 런치하는 PendingIntent(계류된 인텐트)를 정의하고 setOnClickPendingIntent(int, PendingIntent)를 가진 App 위젯의 버튼에 그것을 덧붙일 목적을 위해 오직 onUpdated() 메쏘드만을 정의한다. 그것은 appWidgetIds에 있는 각각의 엔트리를 통해 반복되는 루프를 포함하고 있다. appWidgetIds는 AppWidgetProvider에 의해 생성되는 각각의 App 위젯을 식별하는 ID의 배열이다. 이런 방식으로, 사용자가 App 위젯에 대해 하나 이상의 인스턴스를 생성한다면, 그것들은 모두 동시에 업데이트된다. 하지만 오직 하나의 updatePeriodMillis 스케쥴만이 App 위젯의 모든 인스턴스에 대해서 관리될 것이다. 예를 들어 만약 업데이트 스케쥴이 매 두 시간으로 정의되고, App 위젯의 두 번째 인스턴스가 첫 번째 것 뒤에 한 시간 후에 추가된다면, 그것들은 첫 번째 것에 의해 정의된 주기로 둘 다 업데이트될 것이고, 두 번째 업데이트 주기는 무시될 것이다(그것들은 매 시간이 아닌, 매 두 시간마다 둘 다 업데이트될 것이다).

Note: Because the AppWidgetProvider is a BroadcastReceiver, your process is not guaranteed to keep running after the callback methods return (see Application Fundamentals > Broadcast Receiver Lifecycle for more information). 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 Service in the onUpdated() 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 Not Responding (ANR) error. See the Wiktionary sample's AppWidgetProvider for an example of an App Widget running a Service.

Note: AppWidgetProvider가 하나의 BroadcastReceiver이기 때문에, 여러분의 프로세스는 콜백 메쏘드가 리턴된 다음에 계속 실행되는 것이 보장되지 않는다(더 많은 정보에 대해서는, 애플리케이션 기초 > 브로드캐스드 리시버 생명주기를 보라). 만약 여러분의 App 위젯 셋업 프로세스가 수 초 정도를 소요한 후(아마도 웹 요청을 수행하는 동안) 여러분의 프로세스가 계속되어야 한다면, onUpdated() 메쏘드에서 서비스를 시작시키는 것을 고려하라. 그 서비스 내에서, 여러분은 애플리케이션이 응답하지 않음(Application Not Responding, ANR) 에러 때문에 AppWidgetProvider가 강제 종료되는 것에 대한 경고 없이 App 위젯에 대한 여러분 자신의 업데이트를 수행할 수 있다. App 위젯이 서비스를 실행하는 예제에 대해서는, Wiktionary 샘플의 AppWidgetProvider를 보라.

Also see the ExampleAppWidgetProvider.java sample class.

또한 ExampleAppWidgetProvider.java 샘플 클래스를 보라.

Receiving App Widget broadcast Intents

AppWidgetProvider is just a convenience class. If you would like to receive the App Widget broadcasts directly, you can implement your own BroadcastReceiver or override the onReceive(Context, Intent) callback. The four Intents you need to care about are:

AppWidgetProvider는 꽤 편리한 클래스이다. 만약 여러분이 App 위젯 브로드캐스트를 직접적으로 수신하고자 한다면, 여러분 자신의 Broadcast Receiver를 구현하거나 또는 onReceive(Context, Intent) 콜백을 오버라이드 할 수 있다. 여러분이 관심을 기울일 필요가 있는 4가지 인텐트가 아래에 있다.

  • ACTION_APPWIDGET_UPDATE
  • ACTION_APPWIDGET_DELETED
  • ACTION_APPWIDGET_ENABLED
  • ACTION_APPWIDGET_DISABLED

Creating an App Widget Configuration Activity

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 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, update period or other functionality settings.

만약 여러분이 사용자로 하여금 새로운 App 위젯을 추가할 때 셋팅을 설정하게 하고자 한다면, 여러분은 App 위젯 설정configuration 액티비티를 생성할 수 있다. 이 액티비티는 App 위젯 호스트에 의해 자동으로 시작될 것이며, 사용자가 App 위젯 생성 시점에 App 위젯의 색, 크기, 업데이트 주기, 또는 다른 기능 설정들과 같은 App 위젯에 대한 유용한 셋팅들을 설정하는 것을 가능하게 한다.

The configuration Activity should be declared as a normal Activity in the Android manifest file. However, it will be launched by the App Widget host with the ACTION_APPWIDGET_CONFIGURE action, so the Activity needs to accept this Intent. For example:

이 설정configuration 액티비티는 AndroidManifest.xml에 일반적인 액티비티로 정의되어야 한다. 하지만 그것은 ACTION_APPWIDGET_CONFIGURE 액션을 가지고 App 위젯 호스트에 의해 시작될 것이다. 그러므로 그 액티비티는 이 인텐트를 받아들이는 것이 필요하다. 예를 들어 다음과 같다.

<activity android:name=".ExampleAppWidgetConfigure">
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
    </intent-filter>
</activity>

Also, the Activity must be declared in the AppWidgetProviderInfo XML file, with the android:configure attribute (see Adding the AppWidgetProvierInfo Metadata above). For example, the configuration Activity can be declared like this:

또한 그 액티비티는 AppWidgetProvider XML 파일에 android:configure 애트리뷰트를 가지고 정의되어야 한다(앞에서 언급된 AppWidgetProviderInfo 메타 데이터 추가하기를 보라). 예를 들어 설정configuration 액티비티는 다음과 같이 선언될 수 있다.

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:configure="com.example.android.ExampleAppWidgetConfigure" 
    ... >
</appwidget-provider>

Notice that the Activity is declared with a fully-qualified namespace, because it will be referenced from outside your package scope.

액티비티가 전체 이름fully-qualified의 네임스페이스를 가지고 정의되는 것에 주의하라. 왜냐하면, 그것은 여러분의 패키지 영역 밖에서 레퍼런스될 것이기 때문이다.

That's all you need to get started with a configuration Activity. Now all you need is the actual 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 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 EXTRA_APPWIDGET_ID).
  • The 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, onUpdate() will be called for subsequent updatesit is only skipped the first time.
  • App 위젯 호스트는 설정configuration 액티비티를 호출하며, 설정configuration 액티비티는 항상 결과를 리턴해야 한다. 결과는 액티비티를 시작했던 인텐트에 의해 전달된 (EXTRA_APPWIDGET_ID 로 인텐트 엑스트라에 저장된) App 위젯 ID를 포함해야 한다.
  • onUpdate() 메쏘드는 App 위젯이 생성될 때 호출되지 않을 것이다(시스템은 설정(configuration) 액티비티가 시작될 때, ACTION_APPWIDGET_UPDATE 브로드캐스트를 보내지 않을 것이다). App 위젯이 최초로 생성될 때, AppWidgetProvider로부터 업데이트를 요청하는 것은 설정configuration 액티비티의 책임이다. 하지만 onUpdate()는 이어지는 업데이트들에 대해서 호출될 것이다. 그것은 오직 첫 번째에만 건너뛰어진다.

See the code snippets in the following section for an example of how to return a result from the configuration and update the App Widget.

그 설정configuration에서 결과를 리턴하는 방법과 App 위젯을 업데이트 하는 방법의 예제에 대해, 다음 섹션에 있는 코드 단편snippet들을 보라.

Updating the App Widget from the 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 AppWidgetManager.

App 위젯이 설정configuration 액티비티를 사용할 때, 설정configuration이 완료될 때 App 위젯을 업데이트하는 것은 그 설정configuration 액티비티의 책임이다. 여러분은 AppWidgetManager로부터 직접적으로 업데이트를 요청함으로써 그렇게 할 수 있다.

Here's a summary of the procedure to properly update the App Widget and close the configuration Activity:

여기에 App 위젯을 적절하게 업데이트 하고 설정configuration 액티비티를 종료하는 절차에 대한 요약이 있다.

  1. First, get the App Widget ID from the Intent that launched the Activity:
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) {
        mAppWidgetId = extras.getInt(
                AppWidgetManager.EXTRA_APPWIDGET_ID, 
                AppWidgetManager.INVALID_APPWIDGET_ID);
    }
    
  2. Perform your App Widget configuration.
  3. When the configuration is complete, get an instance of the AppWidgetManager by calling getInstance(Context):
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    
  4. Update the App Widget with a RemoteViews layout by calling updateAppWidget(int, RemoteViews):
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.example_appwidget);
    appWidgetManager.updateAppWidget(mAppWidgetId, views);
    
  5. Finally, create the return Intent, set it with the Activity result, and finish the Activity:
  6. Intent resultValue = new Intent();
    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
    setResult(RESULT_OK, resultValue);
    finish();
    
  1. 먼저, 액티비티를 런치했던 인텐트로부터 App 위젯 ID를 얻어라.
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) {
        mAppWidgetId = extras.getInt(
                AppWidgetManager.EXTRA_APPWIDGET_ID, 
                AppWidgetManager.INVALID_APPWIDGET_ID);
    }
    
  2. 여러분의 App 위젯 설정configuration을 수행하라.
  3. 설정configuration이 완료될 때, getInstance(Context) 를 호출해서 AppWidgetManager의 인스턴스를 얻어라.
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    
  4. updateAppWidget(int, RemoteViews)를 호출해서 리모트뷰RemoteViews 레이아웃을 가지고 App 위젯을 업데이트하라.
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.example_appwidget);
    appWidgetManager.updateAppWidget(mAppWidgetId, views);
    
  5. 마지막으로, 리턴 인텐트를 생성하고, 그것에 액티비티 결과result를 설정하고, 그리고 액티비티를 종료finish시켜라.
    Intent resultValue = new Intent();
    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
    setResult(RESULT_OK, resultValue);
    finish();
    

Tip: When your configuration Activity first opens, set the Activity result to RESULT_CANCELED. This way, if the user backs-out of the Activity before reaching the end, the App Widget host is notified that the configuration was cancelled and the App Widget will not be added.

Tip: 여러분의 설정configuration 액티비티가 처음 오픈될 때 액티비티 결과(result)를 RESULT_CANCELED로 설정하라. 이 방식은, 만약 사용자가 끝에 도달하기 전에 액티비티를 back-out하면, App 위젯 호스트는 그 설정이 취소되었다는 것을 통보받고 App 위젯이 추가되지 않을 것이다.

See the ExampleAppWidgetConfigure.java sample class in ApiDemos for an example.

예제에 대해서는 ApiDemos에 있는 ExampleAppWidgetConfigure.java 샘플 클래스를 보라.

↑ Go to top