------

[ AD ] Port Monitor ( Try to use a Best WebSite Monitoring Tool )

------
어플리케이션 구성품
Application Components
  1. Activating components: intents : 컴포넌트 활성화(실행) : 인텐트
  2. Shutting down components : 컴포넌트 죽이기
  3. The manifest file  : 명세서 파일
  4. Intent filters : 활성화 필터


Application Components


안드로이드의 중심 특징은 하나의 애플리케이션이 다른 애플리케이션의 엘리먼트를(단, 그 엘리먼트의 애플리케이션이 사용을 허가하는 조건하에서) 사용할 수 있다는 것이다.

예를 들어 만약 여러분의 애플리케이션이 이미지 스크롤 리스트를 표시할 필요가 있고, 다른 애플리케이션이 그에 알맞은 스크롤러scroller를 개발했고 또한 그것을 다른 애플리케이션이 사용할 수 있도록 만들어 놓았다면, 여러분은 자신의 스크롤러를 별도로 개발하지 않고 이미 있는 스크롤러가 그 작업을 수행할 수 있도록 호출할 수 있다. 이를 위해, 여러분의 애플리케이션은 다른 애플리케이션의 코드를 통합하거나 링크하지는 않는다. 오히려 그것이 필요할 때 다른 애플리케이션 내에 있는 해당 영역piece을 간단하게 구동start-up시킬 수 있다.


A central feature of Android is that one application can make use of elements of other applications (provided those applications permit it).

For example, if your application needs to display a scrolling list of images and another application has developed a suitable scroller and made it available to others, you can call upon that scroller to do the work, rather than develop your own. Your application doesn't incorporate the code of the other application or link to it. Rather, it simply starts up that piece of the other application when the need arises.

이런 작업을 위해서는, 어떤 애플리케이션의 특정 영역이 필요해 질 때 시스템은 애플리케이션 프로세스를 시작할 수 있어야 하며, 그리고 그 영역에 대한 Java 오브젝트를 인스턴스화 할 수 있어야 한다. 그러므로 다른 대부분 시스템에서의 애플리케이션과는 달리, 안드로이드는 애플리케이션 안의 모든 것들에 대한 하나의 시작점entry point을 가지지 않는다(예를 들어 main() 함수가 없음). 대신에, 안드로이드 애플리케이션에는 시스템이 그것을 필요로 할 때 인스턴스화하고 실행할 수 있는 기본적인 컴포넌트들이 존재한다.

안드로이드 애플리케이션에는 네 가지 유형의 컴포넌트가 존재한다.

For this to work, the system must be able to start an application process when any part of it is needed, and instantiate the Java objects for that part. Therefore, unlike applications on most other systems, Android applications don't have a single entry point for everything in the application (no main() function, for example). Rather, they have essential components that the system can instantiate and run as needed.

There are four types of components:

Activities

액티비티는 사용자가 착수할 수 있는 하나의 포커스된 시도에 대한 비쥬얼사용자 인터페이스를 나타낸다.

예를 들어 액티비티는 사용자들이 선택할 수 있는 메뉴 아이템 리스트를 나타내거나, 사진과 함께 그것의 캡션caption을 나타낼 수도 있다. 텍스트 메시징 애플리케이션은, 메시지를 보내기 위한 컨택contact 리스트를 보여주는 하나의 액티비티와 선택된 컨택contact에 대해 메시지를 작성하는 두 번째 액티비티, 그리고 오래된 메시지들을 다시 보거나 설정을 바꾸기 위한 나머지 액티비티를 가질 수 있다. 이들 액티비티들은 하나의 결합된 사용자 인터페이스를 형성하기 위해 함께 동작함에도 불구하고, 각각의 액티비티는 다른 액티비티와 독립되어 있다. 각각의 액티비티는 Activity 베이스 클래스의 서브클래스로 구현된다.

하나의 애플리케이션은 단지 한 개의 액티비티로 구성될 수도 있으며, 또한 앞서 간단히 언급했던 텍스트 메시징 애플리케이션처럼 몇 개의 액티비티를 포함하고 있을 수도 있다. 당연히 애플리케이션을 구성하는 액티비티가 무엇인지 그리고 얼마나 많은 액티비티가 그곳에 있는 지는, 그 애플리케이션과 그것의 디자인에 의존적이다. 일반적으로 액티비티들 중 하나에는, 그 애플리케이션이 시작됐을 때 사용자에게 보여질 수 있도록 첫 번째 액티비티라는 표시가 붙게 된다. 하나의 액티비티에서 또 다른 액티비티로의 이동은, 현재 액티비티가 다음번 액티비티를 시작함으로써 이루어진다.

각각의 액티비티에는 그리기draw가 가능한 하나의 디폴트 윈도우가 부여된다. 일반적으로 윈도우는 스크린 전체를 채우지만 스크린보다 작을 수도 있고, 다른 윈도우 그 위에 떠있을 수도 있다. 하나의 액티비티는 또한 추가적인 윈도우를 사용할 수 있다 - 예를 들어 액티비티의 한복판에서 사용자 응답을 요청하는 팝업 다이얼로그dialog라든지, 또는 스크린 상에서 특정 아이템을 선택할 때 사용자에게 필수적인 정보를 표시하는 윈도우가 그것이다.

윈도우 내의 비쥬얼visual 컨텐트는 - 베이스 뷰 클래스로부터 파생된 오브젝트들인 - 뷰View들의 계층구조hierarchy에 의해 만들어진다. 각각의 뷰는 윈도우 내의 하나의 특정 직사각형 영역을 제어한다. 부모Parent 뷰은 그것들의 자식들children의 레이아웃을 포함하고 구조화한다. 계층구조의 최하단의 뷰는 그것들이 제어하는 직사각형 영역을 그리며, 그 영역에 국한된 사용자 액션에 대한 책임을 진다. 이와 같이 뷰는 액티비티와 사용자 간의 상호작용이 이루어지는 영역이다. 예를 들어 하나의 뷰는 작은 이미지를 보여줄 수도 있고, 사용자가 그 이미지를 만질 때 특정 액션을 일으킬 수도 있다. 안드로이드는 여러분이 사용할 수 있는 - 버튼, 텍스트 필드, 스크롤 바, 메뉴 아이템, 체크 박스, 그리고 추가적인 것들을 포함해서 - 이미 만들어진 많은 뷰를 가지고 있다.

뷰 계층구조는 Activity.setContentView() 메쏘드에 의해 액티비티의 윈도우 내에 위치하게 된다. 그 컨텐트 뷰는 그 계층구조의 최상위에 있는 뷰view 오브젝트이다(뷰와 계층구조에 대한 더 많은 정보에 대해서는, 3장. “사용자 인터페이스”를 보라).


 

Activities
An activity presents a visual user interface for one focused endeavor the user can undertake. For example, an activity might present a list of menu items users can choose from or it might display photographs along with their captions. A text messaging application might have one activity that shows a list of contacts to send messages to, a second activity to write the message to the chosen contact, and other activities to review old messages or change settings. Though they work together to form a cohesive user interface, each activity is independent of the others. Each one is implemented as a subclass of the Activity base class.

An application might consist of just one activity or, like the text messaging application just mentioned, it may contain several. What the activities are, and how many there are depends, of course, on the application and its design. Typically, one of the activities is marked as the first one that should be presented to the user when the application is launched. Moving from one activity to another is accomplished by having the current activity start the next one.

Each activity is given a default window to draw in. Typically, the window fills the screen, but it might be smaller than the screen and float on top of other windows. An activity can also make use of additional windows — for example, a pop-up dialog that calls for a user response in the midst of the activity, or a window that presents users with vital information when they select a particular item on-screen.

The visual content of the window is provided by a hierarchy of views — objects derived from the base View class. Each view controls a particular rectangular space within the window. Parent views contain and organize the layout of their children. Leaf views (those at the bottom of the hierarchy) draw in the rectangles they control and respond to user actions directed at that space. Thus, views are where the activity's interaction with the user takes place. For example, a view might display a small image and initiate an action when the user taps that image. Android has a number of ready-made views that you can use — including buttons, text fields, scroll bars, menu items, check boxes, and more.

A view hierarchy is placed within an activity's window by the Activity.setContentView() method. The content view is the View object at the root of the hierarchy. (See the separate User Interface document for more information on views and the hierarchy.)

Services

서비스는 비쥬얼한 사용자 인터페이스를 가지지 않는다.

하지만 오히려 정해지지 않은 시간동안 백그라운드background에서 실행된다. 예를 들어 서비스는 사용자가 다른 일에 주의를 기울이는 동안에 백그라운드 음악을 재생할 수 있다. 또한 그것은 네트워크 상에서 데이터를 가져오거나, 또는 어떤 것을 계산해서 그 결과를 필요로 하는 액티비티에게 제공할 수도 있다. 각각의 서비스는 Service 베이스 클래스를 확장extend한다.

이것의 기본적인 예제는 재생 목록에서 음악을 재생하는 미디어 플레이어이다. 아마도 그 플레이어 애플리케이션은 사용자에게 음악을 선택할 수 있게 하고 그것을 재생하는, 하나 또는 그 이상의 액티비티를 가지고 있을 수 있다. 하지만 음악 재생 그 자체는 액티비티에 의해 제어되어서는 안된다. 왜냐하면 사용자가 플레이어 화면을 벗어난 후, 다른 어떤 것을 실행한 이후에도 그 음악이 계속 재생되길 기대할 것이기 때문이다. 음악이 계속 재생되게 하기 위해, 미디어 플레이어 액티비티는 백그라운드에서 실행되는 하나의 서비스를 시작할 수 있다. 시스템은 심지어 그 서비스를 시작했던 액티비티가 스크린에서 사라진 후 조차도 음악 재생 서비스를 계속 유지할 것이다.

실행되고 있는 서비스에 접속connect하는 것(바인드하는 것)이 (그리고 만약 아직 실행되지 않았다면, 그 서비스를 실행하는 것이) 가능하다. 그것에 접속되어 있는 동안, 여러분은 그 서비스가 제공하는 인터페이스를 통해 서비스와 커뮤니케이션할 수 있다. 음악 서비스의 경우, 이러한 인터페이스는 사용자에게 음악을 일시 멈추고, 되감고, 정지시키고, 다시 재생하는 것을 가능하게 한다.

액티비티와 다른 컴포넌트 처럼, 서비스도 애플리케이션 프로세스의 메인 쓰레드 내에서 실행된다. 그러므로 서비스가 다른 컴포넌트 또는 사용자 인터페이스에 의해 방해받지 않도록 하기 위해서 음악 재생같이 시간을 요하는 작업들을 위해서는 종종 또 다른 쓰레드를 만들어서 작동시킨다. 이 부분에 대해서는 추후 언급되는 “프로세스와 쓰레드”를 보라.

Services
A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it. Each service extends the Service base class.

A prime example is a media player playing songs from a play list. The player application would probably have one or more activities that allow the user to choose songs and start playing them. However, the music playback itself would not be handled by an activity because users will expect the music to keep playing even after they leave the player and begin something different. To keep the music going, the media player activity could start a service to run in the background. The system would then keep the music playback service running even after the activity that started it leaves the screen.

It's possible to connect to (bind to) an ongoing service (and start the service if it's not already running). While connected, you can communicate with the service through an interface that the service exposes. For the music service, this interface might allow users to pause, rewind, stop, and restart the playback.

Like activities and the other components, services run in the main thread of the application process. So that they won't block other components or the user interface, they often spawn another thread for time-consuming tasks (like music playback). See Processes and Threads, later.

Broadcast receivers
 브로드캐스트 리시버는 아무 것도 하지 않는 컴포넌트지만, 브로드캐스트 공지를 수신하고 응답한다.

많은 브로드캐스트는 시스템 코드에서 발생된다 - 예를 들어 시간대가 바뀌었다, 배터리가 부족하다, 사진이 찍혔다, 사용자가 언어 설정을 바꾸었다 등이 그것이다. 애플리케이션 또한 브로드캐스트를 발생시킬 수 있다 - 예를 들어 다른 애플리케이션에게 어떤 데이터가 디바이스에 다운로드되었고, 그것들이 그것을 사용하는 것이 가능하다는 것을 알게 할 수 있다.

애플리케이션은 중요하다고 여겨지는 임의의 공지에 응답할 수 있는 임의의 수의 브로드캐스트 리시버를 가질 수 있다. 모든 리시버는 Broadcast Receiver 베이스 클래스를 확장extend한다.

브로드캐스트 리시버는 사용자 인터페이스를 보여주지 않는다. 하지만 그것이 수신한 정보에 응답하는 액티비티를 시작하거나, 또는 사용자에게 알려주기 위해 노티피케이션 매니저notification manager를 사용할 수 있다. 노티피케이션은 여러가지 방법으로 사용자의 주의를 끌 수 있다 - 배경조명 발광, 디바이스 진동, 사운드 재생 등이 있다. 그것은 일반적으로 상태바status bar 내에 아이콘을 상주시켜 놓으며, 사용자는 그 메시지를 얻기 위해 그것을 오픈할 수 있다.


 
Broadcast receivers
A broadcast receiver is a component that does nothing but receive and react to broadcast announcements. Many broadcasts originate in system code — for example, announcements that the timezone has changed, that the battery is low, that a picture has been taken, or that the user changed a language preference. Applications can also initiate broadcasts — for example, to let other applications know that some data has been downloaded to the device and is available for them to use.

An application can have any number of broadcast receivers to respond to any announcements it considers important. All receivers extend the BroadcastReceiver base class.

Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive, or they may use the NotificationManager to alert the user. Notifications can get the user's attention in various ways — flashing the backlight, vibrating the device, playing a sound, and so on. They typically place a persistent icon in the status bar, which users can open to get the message.

Content providers

컨텐트 프로바이더는 다른 애플리케이션에게 유용한 특정 애플리케이션의 데이터 집합을 만든다.

그 데이터는 파일 시스템 내, SQLite 데이터베이스 내, 또는 의미있는 다른 어떤 방식으로 저장될 수도 있다. 컨텐트 프로바이더는 자신이 제어하는 타입의 데이터를 다른 애플리케이션이 얻고 저장할 수 있도록 하게 하는 표준 메쏘드 집합set을 구현하기 위해, ContentProvider 베이스 클래스를 확장extend한다. 하지만 애플리케이션은 이러한 메쏘드를 직접적으로 호출하지 않는다. 대신 애플리케이션은 컨텐트 리졸버ContentResolver 오브젝트를 사용하여 그것의 메쏘드를 호출한다. 컨텐트 리졸버는 어떤 컨텐트 프로바이더와도 대화할 수 있으며, 그것과 관련된 임의의 프로세스 간 통신(IPC, interprocess communication)을 관리하기 위해 프로바이더와 협력한다. 컨텐트 프로바이더 사용법에 관한 더 많은 정보는 7장. 컨텐트 프로바이더를 보라.
Content providers
A content provider makes a specific set of the application's data available to other applications. The data can be stored in the file system, in an SQLite database, or in any other manner that makes sense. The content provider extends the ContentProvider base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls. However, applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead. A ContentResolver can talk to any content provider; it cooperates with the provider to manage any interprocess communication that's involved.

See the separate Content Providers document for more information on using content providers.

특정 컴포넌트에 의해 처리되어야 하는 요청이 있을 때마다, 안드로이드는 그 컴포넌트의 애플리케이션 프로세스가 실행되도록 하며, 필요하다면 그것을 시작하기도 한다. 그리고 그 컴포넌트에 맞는 인스턴스가 사용가능해지도록 하며, 필요하다면 그 인스턴스를 생성도 한다.


Whenever there's a request that should be handled by a particular component, Android makes sure that the application process of the component is running, starting it if necessary, and that an appropriate instance of the component is available, creating the instance if necessary.



Activating components: intents (시작)

Content providers are activated when they're targeted by a request from a ContentResolver. The other three components — activities, services, and broadcast receivers — are activated by asynchronous messages called intents. An intent is an Intent object that holds the content of the message. For activities and services, it names the action being requested and specifies the URI of the data to act on, among other things. For example, it might convey a request for an activity to present an image to the user or let the user edit some text. For broadcast receivers, the Intent object names the action being announced. For example, it might announce to interested parties that the camera button has been pressed.

There are separate methods for activating each type of component:

  • An activity is launched (or given something new to do) by passing an Intent object to Context.startActivity() or Activity.startActivityForResult(). The responding activity can look at the initial intent that caused it to be launched by calling its getIntent() method. Android calls the activity's onNewIntent() method to pass it any subsequent intents.

    One activity often starts the next one. If it expects a result back from the activity it's starting, it calls startActivityForResult() instead of startActivity(). For example, if it starts an activity that lets the user pick a photo, it might expect to be returned the chosen photo. The result is returned in an Intent object that's passed to the calling activity's onActivityResult() method.

  • A service is started (or new instructions are given to an ongoing service) by passing an Intent object to Context.startService(). Android calls the service's onStart() method and passes it the Intent object.

    Similarly, an intent can be passed to Context.bindService() to establish an ongoing connection between the calling component and a target service. The service receives the Intent object in an onBind() call. (If the service is not already running, bindService() can optionally start it.) For example, an activity might establish a connection with the music playback service mentioned earlier so that it can provide the user with the means (a user interface) for controlling the playback. The activity would call bindService() to set up that connection, and then call methods defined by the service to affect the playback.

    A later section, Remote procedure calls, has more details about binding to a service.

  • An application can initiate a broadcast by passing an Intent object to methods like Context.sendBroadcast(), Context.sendOrderedBroadcast(), and Context.sendStickyBroadcast() in any of their variations. Android delivers the intent to all interested broadcast receivers by calling their onReceive() methods.

For more on intent messages, see the separate article, Intents and Intent Filters.

Shutting down components 종료

컨텐트 프로바이더는 컨텐트 리졸버의 요청에 응답하는 동안에만 활성화되어 있다.
그리고 브로드캐스트 리시버도 브로드캐스트 메시지에 응답하는 동안에만 활성화되어 있다.
그러므로 이러한 컴포넌트는 명시적으로 종료시켜야 할 필요가 없다.


A content provider is active only while it's responding to a request from a ContentResolver. And a broadcast receiver is active only while it's responding to a broadcast message. So there's no need to explicitly shut down these components.


반면, 액티비티는 사용자 인터페이스를 제공한다.
이것은 사용자와 오랜시간 동안 대화를 하며 활성화 상태로 남아 있다. 심지어는 대화가 지속될 수 있는 한, 그것이 사용되지 않는idle 상태에도 활성화 상태로 남는다.
유사하게, 서비스 또한 오랜 시간동안 실행 상태로 남아 있다.
그래서 안드로이드는 어떤 규칙적인 방식으로 액티비티와 서비스를 종료시키기 위한 메쏘드를 가지고 있다.

Activities, on the other hand, provide the user interface.
They're in a long-running conversation with the user and may remain active, even when idle, as long as the conversation continues.
Similarly, services may also remain running for a long time.
So Android has methods to shut down activities and services in an orderly way:

  • 액티비티는 finish() 메쏘드의 호출을 통해 스스로 종료될 수 있다.
    그리고 finishActivity()를 호출함으로써, 다른 액티비티(startActivityForResult()를 사용해서 시작된 액티비티)를 종료시킬 수도 있다.
  • 서비스는 stopSelf() 메쏘드의 호출이나 Context.stopService()를 호출함으로써 종료될 수 있다.
    • An activity can be shut down by calling its finish() method.
      One activity can shut down another activity (one it started with startActivityForResult()) by calling finishActivity().
    • A service can be stopped by calling its stopSelf() method, or by calling Context.stopService().

     

    또한, 컴포넌트는 그것이 더 이상 사용되지 않을 때, 또는 안드로이드가 더 많은 활성화된 컴포넌트를 위해 메모리를 회수해야 할 때 시스템에 의해 종료될 수 있다.
    이후에 나오는 “컴포넌트 생명주기” 섹션에서 그것이 일어나는 경우를 좀 더 상세히 논의할 것이다.

    Components might also be shut down by the system when they are no longer being used or when Android must reclaim memory for more active components. A later section, Component Lifecycles, discusses this possibility and its ramifications in more detail.

    The manifest file

    안드로이드는 애플리케이션의 컴포넌트를 시작하기 전에, 컴포넌트의 존재를 인식해야 한다.
    그러므로 애플리케이션은 매니페스트 파일에 그것들의 컴포넌트를 선언한다.
    그리고 그 매니페스트 파일은 안드로이드 패키지, .apk 파일 내에 포함된다.
    이 패키지는 애플리케이션의 코드, 파일, 리소스 또한 보유하고 있다.


    Before Android can start an application component, it must learn that the component exists.
    Therefore, applications declare their components in a manifest file that's bundled into the Android package,
    the .apk file that also holds the application's code, files, and resources.

    The manifest is a structured XML file and is always named AndroidManifest.xml for all applications. It does a number of things in addition to declaring the application's components, such as naming any libraries the application needs to be linked against (besides the default Android library) and identifying any permissions the application expects to be granted.

    But the principal task of the manifest is to inform Android about the application's components. For example, an activity might be declared as follows:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest . . . >
       
    <application . . . >
           
    <activity android:name="com.example.project.FreneticActivity"
                     
    android:icon="@drawable/small_pic.png"
                     
    android:label="@string/freneticLabel"
                      . . .  
    >
           
    </activity>
            . . .
       
    </application>
    </manifest>



    The name attribute of the <activity> element names the Activity subclass that implements the activity. The icon and label attributes point to resource files containing an icon and label that can be displayed to users to represent the activity.

    The other components are declared in a similar way — <service> elements for services, <receiver> elements for broadcast receivers, and <provider> elements for content providers. Activities, services, and content providers that are not declared in the manifest are not visible to the system and are consequently never run. However, broadcast receivers can either be declared in the manifest, or they can be created dynamically in code (as BroadcastReceiver objects) and registered with the system by calling Context.registerReceiver().

    For more on how to structure a manifest file for your application, see The AndroidManifest.xml File.

    Intent filters

    An Intent object can explicitly name a target component. If it does, Android finds that component (based on the declarations in the manifest file) and activates it. But if a target is not explicitly named, Android must locate the best component to respond to the intent. It does so by comparing the Intent object to the intent filters of potential targets. A component's intent filters inform Android of the kinds of intents the component is able to handle. Like other essential information about the component, they're declared in the manifest file. Here's an extension of the previous example that adds two intent filters to the activity:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest . . . >
       
    <application . . . >
           
    <activity android:name="com.example.project.FreneticActivity"
                     
    android:icon="@drawable/small_pic.png"
                     
    android:label="@string/freneticLabel"
                      . . .  
    >
               
    <intent-filter . . . >
                   
    <action android:name="android.intent.action.MAIN" />
                   
    <category android:name="android.intent.category.LAUNCHER" />
               
    </intent-filter>
               
    <intent-filter . . . >
                   
    <action android:name="com.example.project.BOUNCE" />
                   
    <data android:mimeType="image/jpeg" />
                   
    <category android:name="android.intent.category.DEFAULT" />
               
    </intent-filter>
           
    </activity>
            . . .
       
    </application>
    </manifest>

    예제의 첫 번째 필터, 즉 “android.intent.action.MAIN” 액션과 “android.intent.category.LAUNCHER” 카테고리로 구성된 필터는 일반적인 것이다. 이것은 디바이스에서 사용자가 실행할 수 있는 애플리케이션 리스트를 스크린에 보여주는 애플리케이션 런처launcher에 그 액티비티가 표시되게 한다. 달리 말하면, 그 액티비티가 애플리케이션의 시작점이고, 사용자가 런처에서 애플리케이션을 선택했을 때 그들이 처음으로 보게 될 액티비티라는 것을 의미한다.


    The first filter in the example — the combination of the action "android.intent.action.MAIN" and the category "android.intent.category.LAUNCHER" — is a common one. It marks the activity as one that should be represented in the application launcher, the screen listing applications users can launch on the device. In other words, the activity is the entry point for the application, the initial one users would see when they choose the application in the launcher.

    The second filter declares an action that the activity can perform on a particular type of data.

    A component can have any number of intent filters, each one declaring a different set of capabilities. If it doesn't have any filters, it can be activated only by intents that explicitly name the component as the target.

    For a broadcast receiver that's created and registered in code, the intent filter is instantiated directly as an IntentFilter object. All other filters are set up in the manifest.

    For more on intent filters, see a separate document, Intents and Intent Filters.

    + Recent posts