Intent

old/definition 2010. 2. 25. 14:55

An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed. The primary pieces of information in an intent are:

  • action -- The general action to be performed, such as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, etc.

  • data -- The data to operate on, such as a person record in the contacts database, expressed as a Uri.

'old > definition' 카테고리의 다른 글

Context  (0) 2010.02.25
Posted by jazzlife
,

Context

old/definition 2010. 2. 25. 14:54
Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

'old > definition' 카테고리의 다른 글

Intent  (0) 2010.02.25
Posted by jazzlife
,

Vector 클래스는 객체의 가변장 배열을 구현합니다. 여기에는 배열과 같이, 정수 인덱스를 사용해 액세스 할 수 있는 요소가 포함되고 있습니다. 그러나, Vector 사이즈는 작성 후에 추가 및 삭제된 객체를 포함할 수 있도록 필요에 따라서 늘리거나 줄이거나 할 수 있습니다 .

각 Vector는 capacity (용량)와 capacityIncrement (증가량)를 관리하는 것으로써 기억 관리를 최적화하려고 합니다. capacity는 항상 Vector 요소수에 가까운 값이며, 일반적으로 요소수부터 커집니다. 이것은 Vector에 요소가 더해질 때, Vector 기억 영역은 capacityIncrement 만 늘려지기 때문입니다. 많은 요소를 삽입하기 전에 어플리케이션으로 용량을 필요한 값으로 설정해 두면, 메모리의 재배분의 회수를 줄일 수가 있습니다.

Java 2 플랫폼 v1. 2 에서는 이 클래스는 List를 구현하기 위해서 개량되고 있기 때문에 Java Collections Framework 일부가 됩니다. 새로운 컬렉션의 구현과는 달라, Vector는 동기를 잡습니다.

Vector 메서드 Iterator 및 listIterator가 돌려주는 Iterator는 「페이르파스트」입니다. Iterator 작성 후에 Iterator 자체의 remove 또는 add 메서드 이외 방법으로 Vector를 구조적으로 변경하면, Iterator는 ConcurrentModificationException을 Throw 합니다. 따라서, 동시에 변경을 하면, Iterator는 장래의 예측할 수 없는 시점에 있어 예측할 수 없는 동작이 발생하는 위험을 회피하기 위해서 즉시 한편 솜씨 자주 예외를 Throw 합니다. Vector elements 메서드가 돌려주는 Enumeration는 페이르파스트가 아닙니다.

보통, 비동기의 동시 변경이 있는 경우, 확실한 보증을 실시하는 것은 불가능해서, 반복자의 페이르파스트의 동작을 보증할 수 없습니다. 페이르파스트 반복자는 최선 노력 원칙에 기반해 ConcurrentModificationException을 Throw 합니다. 따라서, 정확을 기하기 위해서 이 예외에 존하는 프로그램을 쓰는 것은 잘못입니다. 「반복자의 페이르파스트의 동작은 버그를 검출하기 위해서 마셔 사용해야 합니다」

이 클래스는 Java Collections Framework 멤버입니다.

'old > Data Structure & Algorithm' 카테고리의 다른 글

Hash Table  (0) 2010.02.24
Posted by jazzlife
,
해쉬 테이블 또는 해쉬 맵은 key와 value를 갖는 자료 구조이다. 주요 동작은 효율적인 검색(주어진 키(예를 들어, 사람 이름)로 적합한 값을 찾는(전화번호)) 이다. 해쉬 함수를 이용해서 주어진 키를 해쉬값으로 변환하고 해쉬값을 인덱스로 하여 원하는 값이 있는 버켓(bucket)을 찾아내는 것이다.

1. 시간 복잡도와 해쉬 테이블의 용도

해쉬 테이블은 종종 연관 배열, set, 그리고 캐쉬의 구현에 사용된다. 배열과 비슷하게, 해쉬 테이블은 평균적으로 검색에 테이블 내 아이템의 수와 상관없이 O(1)의 상수 시간 복잡도를 제공한다. 그러나 최악의 경우 검색 시간은 O(n)으로 나빠질 수도 있다. 다른 연관 배열 자료 구조와 비교해, 해쉬 테이블은 많은 수의 자료가 저장될 때 좀 더 유용하며 데이터 셋의 크기를 예측할 수 있을 때 더욱 유용하다.

해쉬 테이블의 검색 성능은 해쉬 함수의 성능과 해쉬 테이블의 크기에 좌우된다. 충돌이 발생하면 할수록 성능은 점점 O(n)에 가까워지므로 충돌을 최대한 억제시키는 것이 해쉬의 핵심 포인트다.


2. 해쉬 함수

좋은 해쉬 함수는 해쉬 테이블 성능 향상에 필수이다. 질 낮은 해쉬 함수는 데이터들의 key를 같은 bucket으로 유도하는 경우가 많아짐으로써 충돌이 증가하고 이는 곧 심각한 해쉬 테이블의 성능 저하로 이어진다.(물론 어떤 구현으로도 충돌을 완전히 피할 수는 없다) 게다가 몇몇 해쉬 함수들은 계산 비용이 너무 많이 들어 상당히 부담스럽다.

좋은 해쉬 함수를 선택하는 것은 상당히 까다로운 일이다. 다른 알고리즘이나 자료구조와는 다르게 해쉬 함수에 대해서는 딱히 정형화된 기준이 없다. 아래에 정리할 해쉬 함수 파트는 3가지 조건 : simplicity, speed, strength 에 초점을 맞출 것이다.

단순성과 속도는 쉽게 측정이 가능하나 strength는 좀 더 애매한 개념이다. SHA-1 같은 cryptographic 해쉬 함수는 상대적으로 느슨한 strength가 필요하나 느린 속도나 복잡한 구조는 상당히 불만족스럽다. 사실 crytographic 해쉬 함수도 악의 있는 공격자에 대한 보호 장치를 제공하지 않아, 특정 해쉬 함수를 쓰기 보다 universal 해쉬 함수가 사용되어지는 경우도 있다.(Universal 해쉬 함수는 공격자에 의해 최악의 성능으로 빠질 수 없도록, 충돌이 너무 자주 일어나지 않도록 보장하는 해쉬 함수를 얘기한다)

표준 방식은 없지만, 대개 해쉬 함수가 avalanche effect를 낼 수 있는지 여부로 해쉬 함수의 strength를 측정한다.(avalanche(눈사태) effect : 입력 데이터를 살짝만 바꿔(ex. flipping single bit) 출력 데이터가 상당히 바뀌는 효과(ex. halfs the output bits flipping))

다행히 위의 3가지 조건을 만족시키는 좋은 해쉬 함수들이 나와 있으며 Jenkins의 One-at-a-time 해쉬 함수가 대표적인 예라 할 수 있다. 32/64비트 int형의 괜찮은 해쉬 함수를 첨부한다. ---> int_hash_func.txt

해쉬 함수를 작성하는 방법에 따라 종류를 분류해보면 분할, 폴딩, 중간-제곱 함수, 추출, 기수 변환 등이 있으며 일반적으로 해쉬 테이블의 크기가 소수(prime number)일 때 성능이 좋아진다.


3. 충돌 해결

두 개의 키가 같은 인덱스로 해싱되면 같은 곳에 저장될 수 없다. 따라서 해싱된 인덱스에 이미 다른 값이 들어 있다면, 새 데이터를 저장할 다른 위치를 찾은 뒤에야 저장할 수 있는 것이다. 100만개의 크기를 가지는 해쉬 테이블에 뛰어난 해쉬 함수로 가지고 있다고 해도, 대략 2500개의 레코드가 찼을 때 충돌이 발생활 확률은 95%에 이른다고 한다.

따라서 충돌 해결은 필수이며 가장 널리 쓰이는 chaining 방식과 open addressing 방식에 대해 알아보자.

1) Chaining

모든 bucket을 연결 리스트로 만들어 충돌이 발생하면 해당 bucket의 list에 추가하는 방식이다. 위 그림에서 보듯이, Smith와 Dee의 해쉬값이 873으로 동일하게 나왔으므로 Smith->Dee의 연결 리스트 형식으로 삽입하는 것이다.

Chaining 방식은 open-addressing 방식에 비해 크게 두 가지 이점을 가진다.

1. 삭제 작업이 간단하다.
2. 모든 버켓이 사용중이더라도 성능 저하가 더디게 나타나므로 open-addressing 방식에 비해 테이블 확장을 상당히 늦출 수 있다.

실제로 많은 chaining 해쉬 테이블에서 확장이 전혀 필요하지 않을 수 있는데, 테이블이 채워지는 것에 비례, 성능 저하가 linear하게 발생하기 때문이다. 예를 들어, chaining 해쉬 테이블에 적정 크기보다 2배의 데이터가 삽입되어도 2배의 속도 저하가 있을 뿐이다.

연결 리스트를 사용하는 chaining 해쉬 테이블은 연결 리스트의 단점도 그래도 물려받아, 작은 데이터들을 저장할 때 연결 리스트 자체의 오버헤드가 부담이 되고 traverse의 캐쉬 효율도 좋지 않다. 대체 자료구조로서 최악의 경우에 O(n)이 아닌 O(log n)의 검색 복잡도를 보장하는 self-balancing tree를 고려해 볼 필요도 있다.

그러나 해쉬 테이블이 꽉 찰 정도로 운영되거나 상당히 높은 확률로 충돌이 발생하지 않는다면(저렇게 되지 않도록 하는 것이 가장 좋다), 통상적으로 리스트의 길이는 대부분 상당히 짧으며 모든 버켓이 2개 이상의 개체를 가지지도 않기 때문에 연결 리스트를 이용한 chained 해쉬 테이블로도 충분히 효과적이다.

그리고 데이터의 크기가 작을 때는 space 오버헤드를 줄이고 캐쉬 효율을 높이기 위해 연결 리스트 대신 dynamic array를 쓸 수도 있다.

2) Open-addressing

Open-addressing 해쉬 테이블은 배열 내에 데이터를 바로 저장할 수 있다.

충돌은 탐사(probing) 방식으로 해결하며 다음과 같은 잘 알려진 probe sequence들이 있다.

1. Linear probing : 순차적으로 탐색하며 비어있는 버켓을 찾을 때까지 계속 진행된다. 최악의 경우, 탐색을 시작한 위치까지 돌아오게 되어 종료(모든 버켓 순회)하게 된다. 캐쉬의 효율은 높으나 데이터의 클러스터링에 가장 취약한 단점이 있다.

2. Quadratic probing : 2차 함수를 이용해 탐색할 위치는 찾는다. 캐쉬의 효율과 클러스터링에 강한 능력에서 linear probing과 double hashing probing의 중간 정도 능력을 가진다.

3. Double hashing probing : 하나의 해쉬 함수에 의해 충돌이 발생하면 2차 해쉬 함수를 이용해 새로운 주소를 할당하는 방법이다. 캐쉬 효율은 3가지 방식 중 가장 좋지 않지만, 클러스터링에 거의 영향을 받지 않는다. 또한 가장 많은 연산량을 요구한다.

탐사 방식에 따라 open-addressing 해쉬의 성능이 달라지지만, 가장 치명적인 영향을 미치는 요소는 바로 해쉬 테이블의 load factor(전체 슬롯에서 사용중인 슬롯 비율)이다. Load factor가 100%로 증가할수록 데이터를 찾거나 삽입하기 위해 필요한 탐사 횟수는 비약적으로(dramatically) 증가한다. 일단 테이블이 꽉 차게 되면 probing이 실패하여 끝나버리기도 한다. 아래 표는 load factor에 따른 평균 성공 탐색수와 실패수이다.

위 표와 같이 아무리 좋은 해쉬 함수를 쓰더라도 일반적으로 load factor는 80%로 제한된다.(자바에서의 Hashmap은 기본 load factor threshold가 75%이다) 클러스터링에 가장 취약한 linear probing 방식이 load factor가 높을수록 가장 급격하게 성능 저하가 발생하는 것을 확인할 수 있다. 따라서 load factor가 임계점을 넘어 큰 경우의 성능은

double hashing > quadratic > linear 의 순서다.

물론 질 낮은 해쉬 함수는 엄청난 클러스터링을 유발함으로써 아주 낮은 load factor에도 해쉬 테이블의 성능을 상당히 낮아지게 한다. 어떤 문제가 해쉬 함수의 클러스터링을 유발하는지 알기는 쉽지 않아도, 해쉬 함수가 심각한 클러스터링을 유발하게 하는 것은 상당히 쉽다. 그냥 잘 만들어진, 그리고 많은 사람들에 의해 충분히 검증된 공개된 함수들을 가져다 쓰자 :-)

3) Chaining vs Open-addressing

Chained 해쉬 테이블은 open-addressing에 비해 다음과 같은 장점을 가진다.

1. 효과적으로 구현하기 간단하고 기본적인 자료구조 정도만 요구된다.
2. 해쉬 함수를 구현(선택)하는 관점에서 볼 때, chained 해쉬 테이블은 클러스터링에 거의 영향을 받지 않아 충돌의 최소화만 중점적으로 살펴보면 된다. 반면에 open-addressing 방식은 클러스터링까지 피해야 하므로 해쉬 함수의 성능에 지대한 영향을 받아 해쉬 함수를 구현(선택)하기가 쉽지 않다.
3. 테이블이 채워져도 성능 저하가 linear하게 발생한다. 비록 테이블이 채워질 수록 chain은 늘어나겠지만(리스트의 길이가 길어지겠지만) near-filled 상태의 open-addressing 방식에서 발생하는 급작스런 lookup 시간의 증가는 발생하지 않는다. (아래 그림을 보자)
4. 데이터의 크기가 대략 5 words and more 이라면, open-addressing 방식보다 적은 메모리를 사용한다.
5. 테이블의 데이터가 산재해 있다면(아주 큰 배열에서 빈 공간이 많은), chained 해쉬 테이블은 연결 리스트 등 테이블 외 별도의 외부 저장 공간에 동적으로 할당하여 사용함으로써 2 ~ 4 words의 작은 데이터라도 미리 공간을 잡아놓고 사용하는 open-addressing 방식보다 적은 메모리를 사용한다.

작은 크기의 데이터에 대해(a few words or less) open-addressing은 chaining에 비해 다음과 같은 장점을 가진다.

1. Open-Addressing 방식은 어떠한 포인터도 저장할 필요가 없고 테이블 외부에 어떠한 추가적인 저장 공간이 필요 없으므로 chaining 방식보다 메모리 효율이 높다.
2. 삽입시 메모리 할당 오버헤드가 없으며, 메모리 할당자가 없이도 구현이 가능하다.
3. 외부에 별도 공간을 필요로 하지 않기 때문에 chaining의 연결 리스트 같은 외부 공간에 필요한 추가적인 작업이 요구되지 않는다. 또한 (특히 linear probing에서) chaining보다 뛰어난 locality of reference(하나의 자원에 여러 번 접근하는 process)를 가진다. 데이터의 크기가 작다면, 특히 lookup에서, 이러한 특성들로 인해 chaining보다 성능이 좋을 수 있는 것이다.
4. 포인터를 사용하지 않음으로써 serialization이 용이하다.

반면에 open-addressing 방식은 큰 데이터를 다뤄야 할 때는 좋지 않은 선택인데, 데이터들이 캐쉬 라인을 채워버릴 것이며(캐쉬의 이득이 없어짐) 많은 공간이 (크기가 큰) 빈 슬롯들에 의해 낭비될 것이다.

정리하자면 open-addressing 방식은 테이블에 모두 저장될 수 있고 캐쉬 라인에 적합할 수 있을 정도로 데이터의 크기가 작을수록 성능이 더 좋아진다. 테이블의 높은 load factor가 예상되거나, 데이터가 크거나, 데이터의 길이가 가변일 때 chained 해쉬 테이블은 open-addressing 방식보다 적어도 동등하거나 훨씬 더 뛰어난 성능을 보인다.

4) Coleasced hashing

Chaining과 open-addressing을 혼합한 방식이며, 테이블 내의 버켓들끼리 서로 chain 링크를 가지게 한다.(Chained 방식은 각 버켓들 마다 고유의 chain 링크를 갖는다)

Open-addressing 처럼, chaining에 비해 storage usage and cache에서 우위를 보인다.
Chaining 처럼, 클러스터링에 거의 영향을 받지 않으며 실제로 테이블이 높은 밀도로 효과적으로 채워질 수 있다.
하지만 chaining과 다르게 버켓끼리 chain 링크를 거는 방식이므로 테이블 슬롯보다 많은 수의 데이터를 저장할 수 없다.


4. Table resizing

성능이 좋은 해쉬 함수를 사용하면 일반적으로 전체 슬롯의 70~80%가 채워져도 해쉬 테이블의 성능은 유지된다. 이 상태에서 더 많은 데이터가 추가되면, 충돌 해결 메커니즘에 따라 gradually or dramatically 하게 성능 저하가 발생한다. 이를 피하기 위해 load factor가 특정 임계점을 돌파하면 더 큰 테이블을 새로 만들어 데이터를 모두 옮기는 방법이 있다.

테이블 확장은 상당히 비용이 많이 드는 작업이며, 확장의 필요성은 해쉬 테이블의 단점 중 하나이다. 아주 무식하게 데이터가 하나씩 삽입될 때마다 매번 테이블을 늘어난 크기만큼 확장시킨다고 가정하면, 성능이 기하급수적으로 떨어질 것이며 더 이상 사용하기 힘든 해쉬 테이블이 될 것이다. 하지만 특정 퍼센트(예를 들어 10%, 100%)로 확장을 한다고 하면, 확장이 자주 발생하지 않아 lookup에 발생하는 평균적인 시간이 O(1)으로 되는 amortized(평소엔 좋지만 최악의 상황도 있는) 복잡도를 갖게 된다.

반면에 특히 real-time 시스템 같은 시스템에서는 테이블을 확장시키는 발생하는 비용을 감당하지 못할 수 있다. 이를 간단하게 해결하려면, 삽입될 데이터의 수보다 아주 큰 테이블을 만들거나 삽입 자체를 너무 많이 못하게 금지시키면 된다. 또 다른 방법으로 유용하지만 more memory-intensive인 기술은 다음과 같이 점진적으로 확장하는 방식이다.

1. 새 해쉬 테이블을 할당하지만 이전 해쉬 테이블을 삭제하지 않고, lookup 과정에서 두 테이블 모두 체크한다.
2. 데이터가 삽입될 때마다 새 테이블에 저장하고 특정 k 만큼 이전 테이블에서 새 테이블로 데이터를 이전한다.
3. k 만큼 데이터를 옮기다가 이전 테이블에 저장된 데이터가 없으면 이전 테이블을 free 한다.

Linear hashing은 incremental 해쉬 테이블 확장을 가능하게 하는 해쉬 테이블 알고리즘이다. 하나의 해쉬 테이블로 구현되지만, 두 개의 유효한 lookup 함수를 가진다.

아무리 훌륭한 방법을 고안, 구현하더라도 확장은 분명 해쉬 테이블의 심각한 성능 저하를 초래할 것이다. 가급적 확장이 일어나지 않도록 해쉬 테이블을 설계하고, 필요하다면 load factor가 일정 이상 늘어나지 않도록 테이블의 데이터 수를 제한하는 것도 확장하는 것보다는 낫다고 생각한다.


5. 해쉬의 단점

해쉬 테이블은 데이터를 pseudo-random 위치에 저장하기 때문에, 데이터를 정렬된 순서로 접근하는 것에 엄청난 비용이 발생한다. Self-balancing binary tree 같은 다른 자료구조에서는 일반적으로 lookup 시간이 O(log n)으로 느리고 구현도 더 복잡하지만 항상 데이터가 정렬되어 있다. 그리고 traverse 능력도 현저히 떨어지는데, 데이터가 산재해 있을 확률이 높은 해쉬 테이블의 특성상 빈 슬롯도 모두 체크하면서 순회를 해야 하기 때문이다.

해쉬 테이블은 일반적으로 locality-of-reference가 취약한데 데이터의 접근 패턴이 기본적으로 해쉬값을 이용한 jump around 방식이기 때문이며, 이는 프로세서의 캐쉬 미스를 발생(cause long delay)시킨다. 데이터의 수가 적고 key type이 integer 처럼 비교하기에 비용이 적게 든다면, linear search를 하는 배열 같은 간단한 자료구조에서 lookup에 더 나은 성능을 보인다.(일반적으로 hash는 개체수가 적을 때 성능이 떨어진다)

또한 해쉬 테이블은 구현 및 사용이 좀 더 어렵고 문제를 수반하기 쉽상이다. 모든 key type에 대해 강력한 해쉬 함수를 요구하는데, 다른 자료 구조의 간단한 비교 함수에 비해 설계하기도 구현하기도 디버그하기도 쉽지 않다. 특히 open-addressing 방식에서는 질 낮은 해쉬 함수를 만들기가 꽤나 쉽다.


6. 결론

하지만 최근 Java 등에서 map이 hashmap으로 대체되는 등, 검색이 주요 동작인 자료구조의 핵심이 되고 있다. 트리의 높이에 탐색 시간이 비례하는 map에 비해 평균적으로 O(1)의 탐색 시간을 보장하는 hashmap이 훨씬 좋음은 두 번 말해 입 아플 정도다.

Hash는 구현하기 어려운 자료구조가 아니나, 아름답게 구현하기는 무척 어려운 편이다. 뛰어난 해쉬 함수를 구현하거나 찾고 원만한 충돌 해결 알고리즘을 사용할 수 있다면 hash는 반드시 강력한 도구가 될 것이다.

'old > Data Structure & Algorithm' 카테고리의 다른 글

Vector Class  (0) 2010.02.24
Posted by jazzlife
,

style

old/UI Design 2010. 2. 22. 20:40

styles.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources>
 
   
<style name="CodeFont" parent="@android:style/TextAppearance.Medium">
 
       
<item name="android:layout_width">fill_parent</item>
 
       
<item name="android:layout_height">wrap_content</item>
 
       
<item name="android:textColor">#00FF00</item>
 
       
<item name="android:typeface">monospace</item>
 
   
</style>
 
</resources>


R.style에서 다양한 속성들을 상속받아서 style로 사용한다.

(ex)
<style name="CodeFont" parent="@android:style/TextAppearance.Medium"> 

<style  name="Theme.CutomDialog" parent="android:style/Theme.Dialog">

 
상속받은 item을 정의 한다.
       
<item name="android:textColor">#00FF00</item> 
<item name="android:typeface">monospace</item>

<item name="android:windowBackground">@drawable/filled_box</item>


다른 곳에서 레이아웃을 불러와서 style을 적용하기도 한다.

[/drawable/filled_box.xml]
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#f0600000"/>
    <stroke android:width="3dp" color="#ffff8080"/>
    <corners android:radius="3dp" />
    <padding android:left="10dp" android:top="10dp"
        android:right="10dp" android:bottom="10dp" />
</shape>


사용하기
<EditText 
   
style="@style/Numbers"     ... />

이런 식으로 activity 전체에 style 적용하기도 한다.

[AndroidManifest.xml]
        <activity android:name=".ActivityCustomDialog"
                  android:label="@string/app_name"
                  android:theme="@style/Theme.CutomDialog">

'old > UI Design' 카테고리의 다른 글

Notification  (0) 2010.06.17
UI 이벤트 처리  (0) 2010.06.15
기본 UI 생성 순서  (0) 2010.02.22
R.anim  (0) 2010.02.22
R.integer  (0) 2010.02.22
Posted by jazzlife
,

1. Layout source를 작성한다.
2. values/strings.xml을 작성한다.
3. values/styles.xml을 작성한다.
4. 그 외 drawable에 필요한 source를 작성한다.
4. src/source를 작성한다.
5. AndroidManifest.xml을 작성하여 연결시킨다.

'old > UI Design' 카테고리의 다른 글

UI 이벤트 처리  (0) 2010.06.15
style  (0) 2010.02.22
R.anim  (0) 2010.02.22
R.integer  (0) 2010.02.22
AlphaAnimation for Fading Animation  (0) 2010.02.22
Posted by jazzlife
,
; ActivityAnimation이라는 class 에서 NextActivity라는 클래스로 I


[Fade in]

startActivity(new Intent(ActivityAnimation.this, NextActivity.class));
      overridePendingTransition(R.anim.fade, R.anim.hold);


[Zoom in]

startActivity(new Intent(ActivityAnimation.this, NextActivity.class));
      overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);


<fade.xml>

<alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="0.0" android:toAlpha="1.0"
       android:duration="@android:integer/config_longAnimTime" />


<hold.xml>

<translate xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromXDelta="0" android:toXDelta="0"
       android:duration="@android:integer/config_longAnimTime" />


<zoom_enter.xml>

<set xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/decelerate_interpolator">
    <scale android:fromXScale="2.0" android:toXScale="1.0"
           android:fromYScale="2.0" android:toYScale="1.0"
           android:pivotX="50%p" android:pivotY="50%p"
           android:duration="@android:integer/config_mediumAnimTime" />
</set>


<zoom_exit.xml>

<set xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:zAdjustment="top">
    <scale android:fromXScale="1.0" android:toXScale=".5"
           android:fromYScale="1.0" android:toYScale=".5"
           android:pivotX="50%p" android:pivotY="50%p"
           android:duration="@android:integer/config_mediumAnimTime" />
    <alpha android:fromAlpha="1.0" android:toAlpha="0"
            android:duration="@android:integer/config_mediumAnimTime"/>
</set>

-----------------------------------------------------------
public void
overridePendingTransition (int enterAnim, int exitAnim)

Since: API Level 5

Call immediately after one of the flavors of startActivity(Intent) or finish() to specify an explicit transition animation to perform next.

Parameters
enterAnim A resource ID of the animation resource to use for the incoming activity. Use 0 for no animation.
exitAnim A resource ID of the animation resource to use for the outgoing activity. Use 0 for no animation.

'old > API_Demo' 카테고리의 다른 글

APP_Activity_Hello World  (0) 2010.03.15
APP_Activity_Forwarding  (0) 2010.03.15
APP_Activity_Dialog  (0) 2010.03.15
APP_Activity_Custom Title  (0) 2010.03.15
APP_Activiy_Custom Dialog  (0) 2010.03.15
Posted by jazzlife
,

[Err] xml파일명 오류.

old/Err 2010. 2. 22. 16:43
xml 파일의 파일명은 a~z 0~9 까지만 써야한다.
즉, 대문자 사용하면 오류난다~ㅠㅠ

'old > Err' 카테고리의 다른 글

[Err] Could not find xxx.apk! Error  (0) 2010.02.18
Posted by jazzlife
,

Animation

Tweened Animation

Android can perform simple animation on a graphic, or a series of graphics. These include rotations, fading, moving, and stretching.

Source file format: XML file, one resource per file, one root tag with no <?xml> declaration

Resource file location: res/anim/some_file.xml

Compiled resource datatype: Resource pointer to an Animation.

Resource reference name:

  • Java: R.anim.some_file
  • XML: @[package:]anim/some_file

Syntax

The file must have a single root element: this will be either a single <alpha>, <scale>, <translate>, <rotate>, interpolator element, or <set> element that holds groups of these elements (which may include another <set>). By default, all elements are applied simultaneously. To have them occur sequentially, you must specify the startOffset attribute.



Elements and Attributes

<set>
A container that can recursively hold itself or other animations. Represents an AnimationSet. You can include as many child elements of the same or different types as you like. Supports the following attribute:

  • shareInterpolator - Whether to share the same Interpolator among all immediate child elements.

<alpha>
A fading animation. Represents an AlphaAnimation. Supports the following attributes:

  • fromAlpha - 0.0 to 1.0, where 0.0 is transparent.
  • toAlpha - 0.0 to 1.0, where 0.0 is transparent.

<scale>
A resizing animation. Represents a ScaleAnimation. You can specify what is the center point of the image (the pinned center), from which it grows outward (or inward), by specifying pivotX and pivotY. So, for example, if these were 0, 0 (top left corner), all growth would be down and to the right. scale supports the following attributes:

  • fromXScale - Starting X size, where 1.0 is no change.
  • toXScale - Ending X size, where 1.0 is no change.
  • fromYScale - Starting Y size, where 1.0 is no change.
  • toYScale - Ending Y size, where 1.0 is no change.
  • pivotX - The X coordinate of the pinned center.
  • pivotY - The Y coordinate of the pinned center.
 
<translate>
A vertical/horizontal motion animation. Represents a TranslateAnimation. Supports the following attributes in any of the following three formats: values from -100 to 100, ending with "%", indicating a percentage relative to itself; values from -100 to 100, ending in "%p", indicating a percentage relative to its parent; a float with no suffix, indicating an absolute value.

  • fromXDelta - Starting X location.
  • toXDelta - Ending X location.
  • fromYDelta - Starting Y location.
  • toYDelta - Ending Y location.
 
<rotate>
A rotation animation. Represents a RotateAnimation. Supports the following attributes:

  • fromDegrees - Starting rotation, in degrees.
  • toDegrees - Ending rotation, in degrees.
  • pivotX - The X coordinate of the center of rotation, in pixels, where (0,0) is the top left corner.
  • pivotY - The Y coordinate of the center of rotation, in pixels, where (0,0) is the top left corner.
 
<interpolator tag>
You can also use any of the interpolator subclass elements defined in R.styleable. Examples include <CycleInterpolator>, <EaseInInterpolator>, and <EaseOutInterpolator>. These objects define a velocity curve that describes how quickly a visual action takes place on a timeline (fast at first and slow later, slow at first and gradually faster, and so on).

In addition to the attributes defined for each element above, the elements <alpha>, <scale>, <translate>, <rotate>, and <set> all support the following attributes (inherited from the Animation class):

duration
Duration, in milliseconds, for this effect.
startOffset
Offset start time for this effect, in milliseconds.
fillBefore
When set true, the animation transformation is applied before the animation begins.
fillAfter
When set true, the animation transformation is applied after the animation ends.
repeatCount
Defines the number of times the animation should repeat.
repeatMode
Defines the animation behavior when it reaches the end and the repeat count is greater than 0. Options are to either restart or reverse the animation.
zAdjustment
Defines the z-axis ordering mode to use when running the animation (normal, top, or bottom).
interpolator
You can optionally set an interpolator for each element to determine how quickly or slowly it performs its effect over time. For example, slow at the beginning and faster at the end for EaseInInterpolator, and the reverse for EaseOutInterpolator. A list of interpolators is given in R.anim. To specify these, use the syntax @android:anim/interpolatorName.

For more discussion and animation code samples, see the discussion in the 2D Graphics document.


(Ex) fade.xml



(Ex) hold.xml



(Ex) zoom_enter.xml



(Ex) zoom_exit.xml


'old > XML Attr' 카테고리의 다른 글

XML Attributes_TextView  (0) 2010.02.22
XML Attributes_LinearLayout  (0) 2010.02.22
Posted by jazzlife
,

R.anim

old/UI Design 2010. 2. 22. 13:11

acclerate_decelerate_interpolator :

accelerate_interpolator :

anticipate_interpolator :

anticipate_overshoot_interpolator :

bounce_interpolator :

decelerate_interpolator :

fade_in :

fade_out :

linear_interpolator :

overshoot_interpolator :

slide_in_left :

slide_out_right :

'old > UI Design' 카테고리의 다른 글

style  (0) 2010.02.22
기본 UI 생성 순서  (0) 2010.02.22
R.integer  (0) 2010.02.22
AlphaAnimation for Fading Animation  (0) 2010.02.22
Dimension  (0) 2010.02.22
Posted by jazzlife
,

R.integer

old/UI Design 2010. 2. 22. 12:21

애니메이션 효과가 진행되는 시간을 지정된 값으로 설정.

Param : (int) config_longAnimTime, config_mediumAnimTime, config_shortAnimTime

(예)

'old > UI Design' 카테고리의 다른 글

style  (0) 2010.02.22
기본 UI 생성 순서  (0) 2010.02.22
R.anim  (0) 2010.02.22
AlphaAnimation for Fading Animation  (0) 2010.02.22
Dimension  (0) 2010.02.22
Posted by jazzlife
,
<alpha>

A fading animation. Represents an AlphaAnimation. Supports the following attributes:


          fromAlpha
- 0.0 to 1.0, where 0.0 is transparent.


          toAlpha
- 0.0 to 1.0, where 0.0 is transparent.




(Ex)


 

'old > UI Design' 카테고리의 다른 글

style  (0) 2010.02.22
기본 UI 생성 순서  (0) 2010.02.22
R.anim  (0) 2010.02.22
R.integer  (0) 2010.02.22
Dimension  (0) 2010.02.22
Posted by jazzlife
,

Dimension

old/UI Design 2010. 2. 22. 12:09
px
Pixels - corresponds to actual pixels on the screen.

in
Inches - based on the physical size of the screen.

mm
Millimeters - based on the physical size of the screen.

pt
Points - 1/72 of an inch based on the physical size of the screen.

dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion.
Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".

sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.

'old > UI Design' 카테고리의 다른 글

style  (0) 2010.02.22
기본 UI 생성 순서  (0) 2010.02.22
R.anim  (0) 2010.02.22
R.integer  (0) 2010.02.22
AlphaAnimation for Fading Animation  (0) 2010.02.22
Posted by jazzlife
,
(1) android:hint 

    Param : 표시할 내용.

       : 힌트로 내용을 표시한다.

(2) android:paddingBottom

    Param : 정수형 dip 값.

       화면에 상대적인 크기로 패딩을 준다.

(3) android:text

    Param : text, @string/name

        (예) "hello" : "hello"를 textview container에 표시
        (예) "@string/name : res/strings.xml에서 id가 name으로 되어 있는 텍스트를 표시

'old > XML Attr' 카테고리의 다른 글

XML Attributes_Animation  (0) 2010.02.22
XML Attributes_LinearLayout  (0) 2010.02.22
Posted by jazzlife
,

Linear Layout

  Linear Layout은 Box model이며 widgets과 child containers의 배치를 정의한다.
  Linear Layout Control을 위해서 다음 5가지 설정을 지원한다.

     
    • orientation,
    • fill model,
    • weight,
    • gravity
    • padding


1. android:orientation

    Param : vertical, horizontal

    "vertical" : 세로로 배치
    "horizontal" : 가로로 배치


2. android:layout_width, android:layout_height

    Param : fill_parent, wrap_content, (예) 125 px

    "fill_parent" : 가능한 영역을 전부 할당하여 표시
    "wrap_content" : 필요한 만큼의 영역만 할당하여 표시
    "-- px" : 예를들어 "125 px" 125 픽셀만큼만 할당하여 표시

3. android:layout_weight

    Param : 정수 값.

    "1", "2"...: 전체 비율에서 설정한 값만큼의 비율로 할당

4. android:layout_gravity

    Param : fill, top, bottom, center, left, right, center_vertical, fill_vertical, center_horizontal, fill_horizontal, dip_vertical, dip_horizontal

    : 정렬 방식을 지정한다.

5. android:padding

    Param : 픽셀 값.

    : widget에 padding을 지정하여 간격을 띄운다.

'old > XML Attr' 카테고리의 다른 글

XML Attributes_Animation  (0) 2010.02.22
XML Attributes_TextView  (0) 2010.02.22
Posted by jazzlife
,

로컬라이징 포멧과 지역선택 변경으로 해결 가능 한 문제이며...

방법은..


1. 제어판>국가 및 언어옵션>국가별옵션탭>표준및 형식을 영어(미국)으로 위치를 미국으로 설정

2. 만약 목록에 없을경우 xp설치시 지원언어가 설치안된경우이므로 상위 언어탭에서

다른언어지원 박스에서 [콤플렉스 스크립트 및 오른쪽 ....(태국어포함)를 ...] 옵션 선택

만약 설치 안되었을시 WindowXP 씨디 넣으라고 합니다.

3. 설치후에 xp의 경우 C:\Documents and Settings\(user)\LocalSettings\Application Data\Android Vista일 경우는 C:\Users\(user)\AppData\Local\Android
에 있는 debug.kestore를 삭제.

4. 이클립스에 새로운 프로젝트를 생성.

5. 컴파일 후 실행.


관련 문제 해결 방안 참고 문서 링크:

http://code.google.com/p/android/issues/detail?id=834

'old > Err' 카테고리의 다른 글

[Err] xml파일명 오류.  (0) 2010.02.22
Posted by jazzlife
,
Activity 실행

메뉴에서 Run/Run Configurations 실행

Android Application에서 오른쪽 마우스 클릭후 New 선택
Name: New_configuration 을 프로젝트에 맞게 변경
Project : Browse후 해당 Project선택
Launch Action : Run시 실행할 Activity를 선택합니다.


(그림 3-1)

새로 작성한 Activity를 실행해 보기 위해서 Launch를 선택하고 List에서 새로생성한 MyActivity를 선택합니다.
Apply 후 Run을 실행하면 Emulator가 아직 떠있지 않다면 자동으로 실행합니다. Emulator는 한번 생성해 놓으면 매번 프로그램을 실행할때 마다 다시 시작시킬필요없이 재사용될 수 있습니다.

Run을 하게 되면 자동으로 Emulator에 이전에 인스톨되어있던 프로그램을 언인스톨하고 새로 작성된 프로그램을 인스톨한 후 선택한 Activity로 실행하여 줍니다.


(그림 3-2)

에뮬레이터를 처음 실행하였을 때 (그림 3-2)와 같은 화면이 나오는데 MENU라고 써져 있는 부분을 클릭하면 프로그램 화면을 볼 수 있습니다. 정상적으로 실행이 되었다면 에뮬레이터에 myactivity.xml에서 작성해주었던 "안녕하세요 모바일 플레이스 안드로이드 강좌 수강생 여러분" 라는 문구가 나타납니다.


(그림 3-3)

다시 프로그램을 실행시킬 때에는 (그림 3-3)에 표시된 아이콘을 누른 후 생성한 Configuration을 선택하면 됩니다.

디버깅

소스 에디터의 왼쪽 부분을 더블 클릭하면 해당 위치에 브레이크 포인트가 설정됩니다. 브레이크 포인트가 설정된 지점에 작은 동그라미가 표시됩니다.


(그림 3-4)

그럼 이제 디버깅 모드로 프로그램을 실행시켜보도록 하겠습니다. (그림 3-5)에 표시된 벌레 모양 아이콘이 디버깅을 위한 실행 버튼입니다.


(그림 3-5)

다이얼로그 창이 뜨는데 확인을 누르면 이클립스가 디버그 상태로 전환됩니다. 이것을 Debug Perspective로 전환되었다고 합니다. 그리고 아까 잡아주었던 브레이크 포인트에 현재 실행이 멈추어 있는 것을 확인할 수 있습니다.


(그림 3-6)

Step Into (F5) : 메서드 속으로 들어가서 실행
Step Over (F6) : 한줄 실행

등 디버깅과 관련된 명령과 아이콘의 모양은 메뉴의 Run에서 확인하실 수 있습니다.

Perspective

소스 변경화면과 디버깅 화면등의 Perspective 전환은 오른쪽 위화면에서 각각 Java와 Debug의 클릭으로 가능합니다. 


(그림 3-7)

안드로이드 개발시 또하나의 유용한 Perspective가 있는데 바로 DDMS입니다. 메뉴의 Windows/Open Perspective에서 DDMS를 선택하면 열수 있습니다. (바로 보이지 않는다면 Other를 클릭하면 선택하실 수 있습니다.)


(그림 3-8)

DDMS Perspective에서는 현재 에뮬레이터 및 단말의 프로세스, 쓰레드, 힙, 파일등의 다양한 정보를 확인할 수 있습니다. 또한 에뮬레이터에서 SMS, 전화, GPS 등을 시뮬레이션할 수도 있습니다.

로그캣

저번 강좌에서 소스에 Log.d("MyTag", "Print Test Log"); 라는 코드를 넣었습니다. 이것은 개발할때 필요한 로그를 출력해주는 역할을 합니다. 디버깅 혹은 DDMS 화면 밑 부분에 LogCat이라는 영역에서 로그를 확인하실 수 있습니다. Print Test Log라고 찍힌 부분을 확인하실 수 있습니다.


(그림 3-9)

그런데 로그가 너무 많이 나와서 복잡합니다. 작성한 어플리케이션에서 나오는 메시지만을 따로 확인하기 위해서 필터를 적용할 수 있습니다. Log.d함수의 첫번째 인자인 Tag부분을 이용해서 가능합니다. 녹색 + 모양을 눌러 Filter를 생성합니다.


(그림 3-10)

Log Filter라는 창에서 Filter Name은 적당히 적은 후, 따로 메시지를 확인할 Tag부분을 "MyTag"로 적어서 OK를 합니다.


(그림 3-11)

이제 LogCat창안에 새로운 필터 탭이 생겨서 MyTag라는 Tag를 가지는 메시지는 따로 분류해서 보여줍니다.


(그림 3-12)

단말 디버깅

안드로이드 실제 단말을 통한 개발은 몇가지 설정만 해준다면 에뮬레이터를 통한 개발과 크게 다르지 않습니다.

단말 상에서 Settings를 실행 Applications/Development로 들어가서 USB debugging과 Stay awake를 체크해줍니다.
그런 후 단말을 USB케이블을 통해서 PC연결해주면 새로운 장치를 찾았다며 드라이버를 설치하라는 화면이 나옵니다.
드라이버는 SDK가 설치된 폴더 밑에 usb_driver라는 폴더에 저장되어있습니다. (1.0 SDK Release2에서 부터 포함되서 나왔습니다.)

정상적으로 드라이버가 설치되었다면 DDMS화면의 왼쪽 윗부분 Devices화면에 Emulator가 아닌 실제 장치가 표시됩니다.


(그림 3-13)

실제 단말상에서 개발시 소스 상에서 추가해줘야 하는 부분이 하나 있습니다. AndroidManifest.xml에 application 태그에서 android:debuggable="true"를 추가해주어야 합니다. 만약 설정해주지 않는다면 Wating For Debugger화면에서 더 이상 진행되지 않습니다.


(그림 3-14)

debuggable tag는 개발시에 넣어두고 실제 릴리즈시에는 삭제해주는 것이 좋습니다. 이제 모든 설정이 끝났고 실제 단말에서도 에뮬레이터에서 디버깅을 하는 것과 동일하게 개발을 하실 수 있습니다.

이번 강좌에서는 안드로이드 개발과 디버깅을 위한 이클립스의 사용법과 단말 세팅까지 살펴보았습니다. 이제 이클립스에 환경과 기본적인 프로젝트 구성에 익숙해지셨을 테니 다음 강좌 부터는 본격적인 개발에 들어가 보도록 하겠습니다.

출처 : http://www.mobileplace.co.kr/android_dev_info/764

'old > Prepare' 카테고리의 다른 글

R.drawable image preview  (0) 2010.03.03
Framework 소스 변경 필요 시  (0) 2010.03.02
시스템 유틸 삭제 및 유저데이터 삭제  (0) 2010.03.02
Sim Card Check 해제  (0) 2010.03.02
이클립스 개발환경 & 사용법  (0) 2010.02.11
Posted by jazzlife
,

프로젝트 생성

이클립스 메뉴에서 File / New /Project 선택
Android / Android Project 선택 후 Next
다음과 같은 창이 뜹니다. 
  
(
그림 2-1)

Project Name :
이클립스에서 프로젝트를 구분해주기 위한 이름
Package Name : 자바 패키지 지정
Activity Name : 기본으로 생성되는 Activity 클래스에 사용될 이름
Application Name : 단말에서 어플리케이션에 사용되는 이름

다음과 같이 입력해보도록 하겠습니다.
MobilePlace Lecture
kr.mobileplace.lecture
Main
MobilePlace

액티비티(Activity)? 안드로이드 어플리케이션의 기본 단위. 보통 사용자가 현재 보고 있는 전체 화면이라고 생각하면 됩니다. 화면의 구성 정보를 가지고 있고 사용자의 입력을 받아서 처리하는 역할을 합니다.

프로젝트 패키지

 기본으로 생성되는 프로젝트 패키지를 펼쳐 보면 다음과 같습니다.


(
그림 2-2)

src : 자바 소스가 위치합니다.

        Main.java : 기본으로 지정해주었던 Activity 클래스

        R.java : 리소스 파일에서 생성되는 클래스로 항상 자동으로 생성되며 직접 수정을 해서는 안됩니다.

res : 어플리케이션에서 필요한 그림, 멀티미디어, 레이아웃, 문자열 등 다양한 리소스 관리

        drawable : 어플리케이션 내에서 사용될 그림 파일들

        layout : Activity의 화면 구성 정보를 담고 있는 xml파일들

        values : 문자열, 배열, , 스타일등 다양한 부가 정보들.

Android Library : 안드로이드 SDK 사용을 위해 포함된 라이브러리


AndroidManifest.xml :
어플리케이션과 구성과 관련된 모든 정보를 담고 있는 파일. 어플리케이션 작성에서 가장 중요한 역할을 하는 파일입니다. 어플리케이션과 Activity의 다양한 설정, 사용권한, 연관된 라이브러리 등 다양한 정보를 포함합니다.

액티비티 생성

새로운 Activity를 직접 작성해보면서 이클립스의 기능을 살펴보도록 하겠습니다.

클래스 생성

먼저 왼쪽 프로젝트 패키지 화면에서 src/kr.mobileplace.lecture 라는 패키지 위에서 마우스 오른쪽 버튼을 클릭합니다. New를 선택하고 Class를 선택합니다.



(
그림 2-3)

새로운 클래스를 생성하는 다이얼로그가 나타납니다. 먼저 Name부분에 새로 작성할 Activity의 클래스 명을 적습니다. MyActivity라고 적고 그 아래 상속할 Superclass의 이름을 적어줍니다. Activity 클래스를 상속할 것이기 때문에 Activity를 적고 오른쪽에 Browse버튼을 클릭합니다.



(
그림 2-4)

그러면 Activity라는 단어를 포함한 모든 클래스가 나열됩니다. Superclass로 사용할 Classandroid.app.Activity를 선택하고 OK를 클릭합니다.



(
그림 2-5)

이제 다시 (그림 2-4) New Java Class화면에서 Finish를 클릭하면 프로젝트 소스에 새로운 클래스에 대한 파일이 생성된 것을 확인할 수 있습니다.

레이아웃 XML 생성

이번에는 액티비티의 화면 구성에 사용되는 레이아웃 파일을 만들어 보겠습니다. res/layout 폴더위에서 오른쪽 마우스 버튼을 클릭한 후 New 에서 File을 선택합니다. 파일이름을 myactivity.xml이라고 설정한 후 OK를 누릅니다. res 밑에 들어가는 파일들은 항상 소문자, 숫자, _ 만으로 구성되어야 하니 유의하시기 바랍니다!


(
그림 2-6)

아직 xml파일의 내용을 작성하지 않아서 빨간 X표시가 붙어있을 것입니다. myactivity.xml을 더블 클릭한 후 myactivity.xml이 에디터 창에 열립니다. 그런 후 에디터 아래쪽에 있는 Layout | myactivity.xml 탭에서 myactivity.xml을 선택하면 xml을 내용을 에디트 할 수 있는 화면이 열립니다.


(
그림 2-7)

일단 레이아웃 파일의 자세한 작성법은 나중에 다루기로 하고 main.xml에 있는 내용을 그대로 복사 넣고 android:text=”” 부분을 사용자 마음대로 수정해 봅니다.


(
그림 2-8)

AndroidManifest 수정

새로운 Activity를 생성하면 항상 AndroidManifest에다가 관련 정보를 등록해야 합니다. AndroidManifest에 넣어주어야 단말이 해당 Activity의 존재를 알 수 있습니다. 그렇지 않으면 단말에서 정상적으로 Activity를 생성할 수 없습니다.

먼저 AndroidManifest.xml을 더블 클릭한 후, 에디터 창의 아래 탭에서 AndroidManifest.xml을 선택합니다. 일단 기존에 생성되어있는 activity 태그 부분을 그대로 복사하여 하나 더 만든 후에 android:name=”” 부분에 새로 생성한 클래스의 이름 “.MyActivity”를 넣습니다. android:label 부분은 titlebar에 출력될 텍스트를 설정하는 부분입니다. 그리고 Main에 있던 category 부분은 일단 제거하고 저장하도록 하겠습니다.


(
그림 2-9)

메서드 오버라이드

자 이제 필요한 파일들은 모두 생성을 했습니다. 이제 생성된 파일들을 실제 동작할 수 있도록 자바 코드를 작성해 보겠습니다. 다시 MyActivity.java 파일로 돌아갑니다.

클래스의 { } 사이를 클릭해서 커서를 위치 시킨 후 오른쪽 마우스 버튼을 클립합니다. 그리고 Source Override/Implement Methods를 클릭합니다.


(
그림 2-10)

생성된 다이얼로그 창에서 오버라이드할 메서드인 onCreate(Bundle)을 찾아서 체크한 후에 OK 하면 MyActivity.java에 해당 메서드를 오버라이드한 코드가 자동으로 생성됩니다.


(
그림 2-11)

이제 오버라이드한 onCreate메서드에 아까 만들었던 myactivity.xml 이라는 레이아웃을 이 Activity의 화면 구성에 사용한다는 코드인 setContentView(R.layout.myactivity); 작성하여 넣습니다. 그 다음 디버그 메시지 출력을 위한 코드인 Log.d(“MyTag”, “Print Test Log”);를 작성하여 넣습니다. 그런데 Log라는 클래스명에서 빨간 밑줄이 그어지며 에러표시가 난 것을 확인하실 수 있습니다. 해당 클래스가 현재 파일에 import되어있지 않기 때문에 발생하는 에러입니다. Log 위에서 오른쪽 마우스를 클릭한 후 SourceAdd Import를 클릭합니다. (단축키로 Ctrl+Shift+M도 사용하실 수 있습니다.) Log클래스가 여러 개 있기 때문에 선택을 위한 다이얼로그가 뜹니다. android.util.Log를 선택합니다.


(
그림 2-12)

이제 기본적인 코드 작성이 끝이 났습니다. 새로 작성한 소스를 실행해보는 일이 남았는데요 다음 강좌에서 계속 하도록 하겠습니다.

Posted by jazzlife
,

MMC/MNC 란?

old/용어정리 2010. 2. 10. 10:54

<MCC/MNC>

 

 

MCC: mobile country code. 국가별로 unique한 값을 가짐.

) 한국: 450, 중국: 460, 일본: 440....

MNC: mobile network code. 사업자 별로 unique한 값을 가짐.

) KTF: 08, SKT: 05

MCC + MNC를 합해서 plmn id라고 부름. 따라서 전 세계 사업자들은 unique plmn id를 가지게 된다.
단말은 초기 셀 search시 이 plmn을 확인해 보고 해당 셀로 camping on을 할지 말지를 결정한다. Home plmn이면 고민할 필요 없이 위치등록 시도하며, equivalent plmn인 경우도 고민 할 필요가 없다. 아닐 경우는 suitable cell이 없는 것으로 인식하고 그에 따른 동작을 하게 된다.
또 단말의 plmn 선택 모드에 따라서도 plmn search 동작이 틀려진다(automatic/manual)

'old > 용어정리' 카테고리의 다른 글

Refactoring - Martin P.  (0) 2010.04.26
Network  (0) 2010.03.24
IMSI 란?  (0) 2010.02.10
URI 란?  (0) 2010.02.10
MIME란?  (0) 2010.02.10
Posted by jazzlife
,

IMSI 란?

old/용어정리 2010. 2. 10. 10:51

An International Mobile Subscriber Identity or IMSI (pronounced /ˈɪmzi/) is a unique number associated with all GSM and UMTS network mobile phone users. It is stored in the SIM inside the phone and is sent by the phone to the network. It is also used for acquiring other details of the mobile in the Home Location Register (HLR) or as locally copied in the Visitor Location Register. To prevent eavesdroppers identifying and tracking the subscriber on the radio interface, the IMSI is sent as rarely as possible and a randomly-generated TMSI is sent instead.

The IMSI is used in any mobile network that interconnects with other networks, in particular CDMA and EVDO networks as well as GSM networks. This number is provisioned in the phone directly or in the R-UIM card (a CDMA analogue equivalent to a SIM card in GSM).

An IMSI is usually 15 digits long, but can be shorter (for example MTN South Africa's old IMSIs that are still being used in the market are 14 digits). The first 3 digits are the Mobile Country Code (MCC), and is followed by the Mobile Network Code (MNC), either 2 digits (European standard) or 3 digits (North American standard). The remaining digits are the mobile station identification number (MSIN) within the network's customer base.

'old > 용어정리' 카테고리의 다른 글

Network  (0) 2010.03.24
MMC/MNC 란?  (0) 2010.02.10
URI 란?  (0) 2010.02.10
MIME란?  (0) 2010.02.10
Schema 란?  (0) 2010.02.09
Posted by jazzlife
,

URI 란?

old/용어정리 2010. 2. 10. 10:39

URI (Uniform Resource Identifier)는 인터넷에 있는 자원을 나타내는 유일한 주소이다. URI의 존재는 인터넷에서 요구되는 기본조건으로서 인터넷 프로토콜에 항상 붙어다닌다. URI는 다음과 같은 요소로 구성된다.

  • 프로토콜 (HTTP 혹은 FTP) + : + // + 호스트이름 + 주소
  • 예: http://ko.wikipedia.org

URI의 하위개념으로 URL, URN 이 있다.

'old > 용어정리' 카테고리의 다른 글

Network  (0) 2010.03.24
MMC/MNC 란?  (0) 2010.02.10
IMSI 란?  (0) 2010.02.10
MIME란?  (0) 2010.02.10
Schema 란?  (0) 2010.02.09
Posted by jazzlife
,

MIME란?

old/용어정리 2010. 2. 10. 10:38

기본적으로 인터넷 전자우편 전송 프로토콜인 SMTP는 7비트 ASCII 문자만을 지원한다. 이것은 7비트 ASCII 문자로 표현할 수 없는 영어 이외의 언어로 쓰인 전자우편은 제대로 전송될 수 없다는 것을 의미한다. MIME은 ASCII가 아닌 문자 인코딩을 이용해 영어가 아닌 다른 언어로 된 전자우편을 보낼 수 있는 방식을 정의한다. 또한 그림, 음악, 영화, 컴퓨터 프로그램과 같은 8비트 바이너리 파일을 전자우편으로 보낼 수 있도록 한다. MIME은 또한 전자우편과 비슷한 형식의 메시지를 사용하는 HTTP와 같은 통신 프로토콜의 기본 구성 요소이다. 메시지를 MIME 형식으로 변환하는 것은 전자우편 프로그램이나 서버 상에서 자동으로 이루어진다.

전자우편의 기본적인 형식은 RFC 2821에서 정의하고 있다. 이 문서는 RFC 822를 대체한다. 이 문서는 텍스트 전자우편의 헤더와 본문의 형식을 명시하고 있으며, 그 중에는 우리에게 익숙한 "To:", "Subject:", "From:", "Date:" 등의 헤더가 포함되어 있다. MIME은 메시지의 종류를 나타내는 content-type, 메시지 인코딩 방식을 나타내는 content-transfer-encoding과 같은 추가적인 전자우편 헤더를 정의하고 있다. MIME은 또한 ASCII가 아닌 문자를 전자우편 헤더로 사용할 수 있도록 규정하고 있다.

MIME은 확장 가능하다. MIME 표준은 새로은 content-type과 또 다른 MIME 속성 값을 등록할 수 있는 방법을 정의하고 있다.

MIME의 명시적인 목표 중 하나는 기존 전자우편 시스템과의 호환성이다. MIME을 지원하는 클라이언트에서 비 MIME가 제대로 표시될 수 있고, 반대로 MIME을 지원하지 않는 클라이언트에서 간단한 MIME 메시지가 표시될 수 있다.

'old > 용어정리' 카테고리의 다른 글

Network  (0) 2010.03.24
MMC/MNC 란?  (0) 2010.02.10
IMSI 란?  (0) 2010.02.10
URI 란?  (0) 2010.02.10
Schema 란?  (0) 2010.02.09
Posted by jazzlife
,
http://mc500.tistory.com/entry/Goole-Android-Build-해-보기-1

'old > Basic' 카테고리의 다른 글

Parcelable Object 1  (0) 2010.07.06
안드로이드 기본 개념  (0) 2010.07.06
JNI (Java Native Interface)  (0) 2010.07.06
how to make sqplite3 table  (0) 2010.02.09
What is Android?  (0) 2010.02.04
Posted by jazzlife
,

[지원 형식]
INTEGER, REAL, TEXT, BLOB

[테이블 만들기]
CREATE TABLE Students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fname TEXT NOT NULL,
lname TEXT NOT NULL );

CREATE TABLE Tests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
testname TEXT,
weight REAL DEFAULT .10 CHECK (weight<=1));

[자료삽입]
INSERT into Students
(fname, lname)
VALUES
('Harry', 'Potter');

INSERT into Tests
(testname, weight)
VALUES
('YourW', .25);

[테이블 조회]
SELECT * FROM Tests;
집계확인
SELECT SUM(weight) FROM Tests;

[조회 결과를 조합하여 출력]
SELECT fname||' '|| lname AS fullname, id FROM Students;

[외부키와 복합키가 있는 테이블 만들기]
CREATE TABLE TestResults (
studentsid INTEGER REFERENCES Students(id),
testid INTEGER REFERENCES Tests(id),
score INTEGER CHECK (score<=100 AND score>=0),
PRIMARY KEY (studentsid, testid));

출력해보기
SELECT studentid, testid, weig FROM TestResults;

[수정하기]
UPDATE TestResults
SET score=50
WHERE studentid=2 AND testid=2;

[지우기]
DELETE FROM TestResults WHERE studentid=2 AND testid=2;
*WHERE로 지정하지 않으면 테이블 전체가 삭제되니 주의

[다중 테이블 질의]
SELECT
Students.fname||' '|| Students.lname AS StudentName,
Tests.testname,
TestResults.score
FROM TestResults
JOIN Students
                   ON (TestResults.studentid=Students.id)

JOIN Tests

                   ON (TestResults.testid=Test.id)

WHERE testid=6;

[계산식 추가]
SELECT
Students.fname||' '|| Students.lname AS StudentName,
SUM((Tests.weight*TestResults.score)) AS TotalWeightedScore
FROM TestResults
JOIN Students
                   ON (TestResults.studentid=Students.id)

JOIN Tests

                   ON (TestResults.testid=Test.id)

WHERE testid=6;


[필터링과 정렬]
SELECT
Students.fname||' '|| Students.lname AS StudentName,
SUM(Tests.weight*TestResults.score) AS TotalWeightedScore
FROM TestResults
JOIN Students
                   ON (TestResults.studentid=Students.id)

JOIN Tests

                   ON (TestResults.testid=Test.id)

GROUP BY TestResults.studentid
ORDER BY TotalWeightedScore DESC;

[하위 질의 활용]
SELECT
Students.fname||' '|| Students.lname AS StudentName,
Students.id AS StudentID,
(SELECT COUNT(*)
FROM TestResults
WHERE TestResults.studentid=Students.id
AND TestResults.score>60)
AS TestsPassed
FROM Students;

[테이블 삭제]
DROP TABLE TestResults;

'old > Basic' 카테고리의 다른 글

Parcelable Object 1  (0) 2010.07.06
안드로이드 기본 개념  (0) 2010.07.06
JNI (Java Native Interface)  (0) 2010.07.06
http://mc500.tistory.com/entry/Goole-Android-Build-해-보  (0) 2010.02.09
What is Android?  (0) 2010.02.04
Posted by jazzlife
,

adb op for sqlite3

old/SQL 2010. 2. 9. 16:42
[쉘 띄우기]
c:\adb shell
c:\adb -s emulator-5554 shell

[DB연결]
# sqlite3 /data/data/...../~.db
sqlite> .quit 또는 .exit

[DB나열]
sqlite> .databases

[Table 나열]
sqlite> .tables

[특정 Table의 index 나열]
sqlite> .indices ~

[테이블의 schema 보기]
sqlite> .schema ~
지정하지 않으면 전체 schema 나열

[출력 결과를 파일로 보내기]
sqlite> .output /data.../~.sql

[데이터 베이스 백업을 위한 덤프]
출력 대상 파일을 지정.
sqlite> .output /data...../~sql
테이블을 덤프
sqlite> .dump ~
콘솔화면에 뿌려보자
sqlite> .output stdout

[파일에 담긴 sql  스크립트의 실행]
sqlite> SELECT * FROM ~1;
sqlite> SELECT * FROM ~2;
sqlite> .read /data...../~.sql
sql스크립트를 실행하여 테이블 ~1과 ~2의 결과를 출력

[구분자를 이용하여 외부 자료 들여오기]
','로 구분되는 CSV 파일형식의 예
sqlite> .separator ,
sqlite> .import /data...../~.csv  ~<테이블명>

[명령 프롬프트에서 sql 명령 수행]
sqlite> .mode column
헤더로 찾기 on
sqlite> .header on
_id 11 전까지 필터링
sqlite> select * from ~ WHERE _id < 11;

[각 열의 너비 조정]
sqlite> .width 5 50

'old > SQL' 카테고리의 다른 글

산술 연산자  (0) 2010.03.12
WHERE절  (0) 2010.03.12
SQL의 기본  (0) 2010.03.12
MSDE 설치 및 시동  (0) 2010.03.12
OSQL의 시동  (0) 2010.03.12
Posted by jazzlife
,

Schema 란?

old/용어정리 2010. 2. 9. 15:50
Schema 란?

DB에서 어떤 목적을 위하여 필요한 여러 개로 구성된 테이블들의 집합을 Schema라 한다.

예를 들어,
쇼핑몰을 구축한다 하자.

쇼핑몰 구성에는 회원정보, 상품정보, 결제 정보, 배송 정보, 마일리지.... 등등에 관한 기능들로 구성된다.

이럴 때, 회원관련 테이블, 상품관련 테이블, 결제관련 테이블 등등...

DB에 관련된 테이블이 각각 만들어 지며,
이렇게 형성된 테이블들의 관계를 묶어서 Schema라 한다.

DATABASE SCHEMA
• USER A가 생성되면 자동적으로 동일한 이름의 SCHEMA A가 생성된다.
• USER A는 SCHEMA A와 관련되어 DATABASE를 ACCESS한다.
그러므로 USER의 이름과 SCHEMA는 서로 바뀌어 쓰일 수 있다.
SCHEMA는 특정 USER와 관련된 OBJECT의 모음이다.

'old > 용어정리' 카테고리의 다른 글

Network  (0) 2010.03.24
MMC/MNC 란?  (0) 2010.02.10
IMSI 란?  (0) 2010.02.10
URI 란?  (0) 2010.02.10
MIME란?  (0) 2010.02.10
Posted by jazzlife
,

<activity>

syntax:
<activity android:allowTaskReparenting=["true" | "false"] 
          android:alwaysRetainTaskState=["true" | "false"] 
          android:clearTaskOnLaunch=["true" | "false"] 
          android:configChanges=["mcc", "mnc", "locale", 
                                 "touchscreen", "keyboard", "keyboardHidden", 
                                 "navigation", "orientation", "fontScale"] 
          android:enabled=["true" | "false"] 
          android:excludeFromRecents=["true" | "false"] 
          android:exported=["true" | "false"] 
          android:finishOnTaskLaunch=["true" | "false"] 
          android:icon="drawable resource" 
          android:label="string resource" 
          android:launchMode=["multiple" | "singleTop" | 
                              "singleTask" | "singleInstance"] 
          android:multiprocess=["true" | "false"] 
          android:name="string" 
          android:noHistory=["true" | "false"]   
          android:permission="string" 
          android:process="string" 
          android:screenOrientation=["unspecified" | "user" | "behind" | 
                                     "landscape" | "portrait" | 
                                     "sensor" | "nosensor"] 
          android:stateNotNeeded=["true" | "false"] 
          android:taskAffinity="string" 
          android:theme="resource or theme" 
          android:windowSoftInputMode=["stateUnspecified", 
                                       "stateUnchanged", "stateHidden", 
                                       "stateAlwaysHidden", "stateVisible", 
                                       "stateAlwaysVisible", "adjustUnspecified", 
                                       "adjustResize", "adjustPan"] >    
    . . . 
</activity>
contained in:
<application>
can contain:
<intent-filter>
<meta-data>
description:
Declares an activity (an Activity subclass) that implements part of the application's visual user interface. All activities must be represented by <activity> elements in the manifest file. Any that are not declared there will not be seen by the system and will never be run.
attributes:
android:allowTaskReparenting
Whether or not the activity can move from the task that started it to the task it has an affinity for when that task is next brought to the front — "true" if it can move, and "false" if it must remain with the task where it started.

If this attribute is not set, the value set by the corresponding allowTaskReparenting attribute of the <application> element applies to the activity. The default value is "false".

Normally when an activity is started, it's associated with the task of the activity that started it and it stays there for its entire lifetime. You can use this attribute to force it to be re-parented to the task it has an affinity for when its current task is no longer displayed. Typically, it's used to cause the activities of an application to move to the main task associated with that application.

For example, if an e-mail message contains a link to a web page, clicking the link brings up an activity that can display the page. That activity is defined by the browser application, but is launched as part of the e-mail task. If it's reparented to the browser task, it will be shown when the browser next comes to the front, and will be absent when the e-mail task again comes forward.

The affinity of an activity is defined by the taskAffinity attribute. The affinity of a task is determined by reading the affinity of its root activity. Therefore, by definition, a root activity is always in a task with the same affinity. Since activities with "singleTask" or "singleInstance" launch modes can only be at the root of a task, re-parenting is limited to the "standard" and "singleTop" modes. (See also the launchMode attribute.)

android:alwaysRetainTaskState
Whether or not the state of the task that the activity is in will always be maintained by the system — "true" if it will be, and "false" if the system is allowed to reset the task to its initial state in certain situations. The default value is "false". This attribute is meaningful only for the root activity of a task; it's ignored for all other activities.

Normally, the system clears a task (removes all activities from the stack above the root activity) in certain situations when the user re-selects that task from the home screen. Typically, this is done if the user hasn't visited the task for a certain amount of time, such as 30 minutes.

However, when this attribute is "true", users will always return to the task in its last state, regardless of how they get there. This is useful, for example, in an application like the web browser where there is a lot of state (such as multiple open tabs) that users would not like to lose.

android:clearTaskOnLaunch
Whether or not all activities will be removed from the task, except for the root activity, whenever it is re-launched from the home screen — "true" if the task is always stripped down to its root activity, and "false" if not. The default value is "false". This attribute is meaningful only for activities that start a new task (the root activity); it's ignored for all other activities in the task.

When the value is "true", every time users start the task again, they are brought to its root activity, regardless of what they were last doing in the task and regardless of whether they used BACK or HOME to last leave it. When the value is "false", the task may be cleared of activities in some situations (see the alwaysRetainTaskState attribute), but not always.

Suppose, for example, that someone launches activity P from the home screen, and from there goes to activity Q. The user next presses HOME, and then returns to activity P. Normally, the user would see activity Q, since that is what they were last doing in P's task. However, if P set this flag to "true", all of the activities on top of it (Q in this case) were removed when the user pressed HOME and the task went to the background. So the user sees only P when returning to the task.

If this attribute and allowTaskReparenting are both "true", any activities that can be re-parented are moved to the task they share an affinity with; the remaining activities are then dropped, as described above.

android:configChanges
Lists configuration changes that the activity will handle itself. When changes that are not listed occur, the activity is shut down and restarted. When a listed change occurs, the activity remains running and its onConfigurationChanged() method is called.

Any or all of the following strings can be used to set this attribute. Values are separated by '|' — for example, "locale|navigation|orientation".

Value Description
"mcc" The IMSI mobile country code (MCC) has changed — that is, a SIM has been detected and updated the MCC.
"mnc" The IMSI mobile network code (MNC) has changed — that is, a SIM has been detected and updated the MNC.
"locale" The locale has changed — for example, the user has selected a new language that text should be displayed in.
"touchscreen" The touchscreen has changed. (This should never normally happen.)
"keyboard" The keyboard type has changed — for example, the user has plugged in an external keyboard.
"keyboardHidden" The keyboard accessibility has changed — for example, the user has slid the keyboard out to expose it.
"navigation" The navigation type has changed. (This should never normally happen.)
"orientation" The screen orientation has changed — that is, the user has rotated the device.
"fontScale" The font scaling factor has changed — that is, the user has selected a new global font size.

All of these configuration changes can impact the resource values seen by the application. Therefore, when onConfigurationChanged() is called, it will generally be necessary to again retrieve all resources (including view layouts, drawables, and so on) to correctly handle the change.

android:enabled
Whether or not the activity can be instantiated by the system — "true" if it can be, and "false" if not. The default value is "true".

The <application> element has its own enabled attribute that applies to all application components, including activities. The <application> and <activity> attributes must both be "true" (as they both are by default) for the system to be able to instantiate the activity. If either is "false", it cannot be instantiated.

android:excludeFromRecents
Whether or not the activity should be excluded from the list of recently launched activities that can be displayed to users — "true" if it should be excluded, and "false" if it should be included. The default value is "false".
android:exported
Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.

The default value depends on whether the activity contains intent filters. The absence of any filters means that the activity can be invoked only by specifying its exact class name. This implies that the activity is intended only for application-internal use (since others would not know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the activity is intended for external use, so the default value is "true".

This attribute is not the only way to limit an activity's exposure to other applications. You can also use a permission to limit the external entities that can invoke the activity (see the permission attribute).

android:finishOnTaskLaunch
Whether or not an existing instance of the activity should be shut down (finished) whenever the user again launches its task (chooses the task on the home screen) — "true" if it should be shut down, and "false" if not. The default value is "false".

If this attribute and allowTaskReparenting are both "true", this attribute trumps the other. The affinity of the activity is ignored. The activity is not re-parented, but destroyed.

android:icon
An icon representing the activity. The icon is displayed to users when a representation of the activity is required on-screen. For example, icons for activities that initiate tasks are displayed in the launcher window. The icon is often accompanied by a label (see the label attribute).

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 activity's icon — whether set here or by the <application> element — is also the default icon for all the activity's intent filters (see the <intent-filter> element's icon attribute).

android:label
A user-readable label for the activity. The label is displayed on-screen when the activity must be represented to the user. It's often displayed along with the activity icon.

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 activity's label — whether set here or by the <application> element — is also the default label for all the activity'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 also be set as a raw string.

android:launchMode
An instruction on how the activity should be launched. There are four modes that work in conjunction with activity flags (FLAG_ACTIVITY_* constants) in Intent objects to determine what should happen when the activity is called upon to handle an intent. They are:

"standard"
"singleTop"
"singleTask"
"singleInstance"

The default mode is "standard".

The modes fall into two main groups, with "standard" and "singleTop" activities on one side, and "singleTask" and "singleInstance" activities on the other. An activity with the "standard" or "singleTop" launch mode can be instantiated multiple times. The instances can belong to any task and can be located anywhere in the activity stack. Typically, they're launched into the task that called startActivity() (unless the Intent object contains a FLAG_ACTIVITY_NEW_TASK instruction, in which case a different task is chosen — see the taskAffinity attribute).

In contrast, "singleTask" and "singleInstance" activities can only begin a task. They are always at the root of the activity stack. Moreover, the device can hold only one instance of the activity at a time — only one such task.

The "standard" and "singleTop" modes differ from each other in just one respect: Every time there's new intent for a "standard" activity, a new instance of the class is created to respond to that intent. Each instance handles a single intent. Similarly, a new instance of a "singleTop" activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created. In other circumstances — for example, if an existing instance of the "singleTop" activity is in the target task, but not at the top of the stack, or if it's at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack.

The "singleTask" and "singleInstance" modes also differ from each other in only one respect: A "singleTask" activity allows other activities to be part of its task. It's at the root of the activity stack, but other activities (necessarily "standard" and "singleTop" activities) can be launched into the same task. A "singleInstance" activity, on the other hand, permits no other activities to be part of its task. It's the only activity in the task. If it starts another activity, that activity is assigned to a different task — as if FLAG_ACTIVITY_NEW_TASK was in the intent.

For more information on launch modes and their interaction with Intent flags, see the Activities and Tasks section of the Application Fundamentals document.

android:multiprocess
Whether an instance of the activity can be launched into the process of the component that started it — "true" if it can be, and "false" if not. The default value is "false".

Normally, a new instance of an activity is launched into the process of the application that defined it, so all instances of the activity run in the same process. However, if this flag is set to "true", instances of the activity can run in multiple processes, allowing the system to create instances wherever they are used (provided permissions allow it), something that is almost never necessary or desirable.

android:name
The name of the class that implements the activity, a subclass of Activity. The attribute value should be a fully qualified class name (such as, "com.example.project.ExtracurricularActivity"). However, as a shorthand, if the first character of the name is a period (for example, ".ExtracurricularActivity"), it is appended to the package name specified in the <manifest> element.

There is no default. The name must be specified.

android:noHistory
Whether or not the activity should be removed from the activity stack and finished (its finish() method called) when the user navigates away from it and it's no longer visible on screen — "true" if it should be finished, and "false" if not. The default value is "false".

A value of "true" means that the activity will not leave a historical trace. It will not remain in the activity stack for the task, so the user will not be able to return to it.

This attribute was introduced in API Level 3.

android:permission
The name of a permission that clients must have to launch the activity or otherwise get it to respond to an intent. If a caller of startActivity() or startActivityForResult() has not been granted the specified permission, its intent will not be delivered to the activity.

If this attribute is not set, the permission set by the <application> element's permission attribute applies to the activity. If neither attribute is set, the activity is not protected by a permission.

For more information on permissions, see the Permissions section in the introduction and another document, Security and Permissions.

android:process
The name of the process in which the activity 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, 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 the activity runs in that process. 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 resource usage.

android:screenOrientation
The orientation of the activity's display on the device. The value can be any one of the following strings:
"unspecified" The default value. The system chooses the orientation. The policy it uses, and therefore the choices made in specific contexts, may differ from device to device.
"landscape" Landscape orientation (the display is wider than it is tall).
"portrait" Portrait orientation (the display is taller than it is wide).
"user" The user's current preferred orientation.
"behind" The same orientation as the activity that's immediately beneath it in the activity stack.
"sensor" The orientation determined by a physical orientation sensor. The orientation of the display depends on how the user is holding the device; it changes when the user rotates the device.
"nosensor" An orientation determined without reference to a physical orientation sensor. The sensor is ignored, so the display will not rotate based on how the user moves the device. Except for this distinction, the system chooses the orientation using the same policy as for the "unspecified" setting.
android:stateNotNeeded
Whether or not the activity can be killed and successfully restarted without having saved its state — "true" if it can be restarted without reference to its previous state, and "false" if its previous state is required. The default value is "false".

Normally, before an activity is temporarily shut down to save resources, its onSaveInstanceState() method is called. This method stores the current state of the activity in a Bundle object, which is then passed to onCreate() when the activity is restarted. If this attribute is set to "true", onSaveInstanceState() may not be called and onCreate() will be passed null instead of the Bundle — just as it was when the activity started for the first time.

A "true" setting ensures that the activity can be restarted in the absence of retained state. For example, the activity that displays the home screen uses this setting to make sure that it does not get removed if it crashes for some reason.

android:taskAffinity
The task that the activity has an affinity for. Activities with the same affinity conceptually belong to the same task (to the same "application" from the user's perspective). The affinity of a task is determined by the affinity of its root activity.

The affinity determines two things — the task that the activity is re-parented to (see the allowTaskReparenting attribute) and the task that will house the activity when it is launched with the FLAG_ACTIVITY_NEW_TASK flag.

By default, all activities in an application have the same affinity. You can set this attribute to group them differently, and even place activities defined in different applications within the same task. To specify that the activity does not have an affinity for any task, set it to an empty string.

If this attribute is not set, the activity inherits the affinity set for the application (see the <application> element's taskAffinity attribute). The name of the default affinity for an application is the package name set by the <manifest> element.

android:theme
A reference to a style resource defining an overall theme for the activity. This automatically sets the activity's context to use this theme (see setTheme(), and may also cause "starting" animations prior to the activity being launched (to better match what the activity actually looks like).

If this attribute is not set, the activity inherits the theme set for the application as a whole — see the <application> element's theme attribute. If that attribute is also not set, the default system theme is used.

android:windowSoftInputMode
How the main window of the activity interacts with the window containing the on-screen soft keyboard. The setting for this attribute affects two things:
  • The state of the soft keyboard — whether it is hidden or visible — when the activity becomes the focus of user attention.
  • The adjustment made to the activity's main window — whether it is resized smaller to make room for the soft keyboard or whether its contents pan to make the current focus visible when part of the window is covered by the soft keyboard.

The setting must be one of the values listed in the following table, or a combination of one "state..." value plus one "adjust..." value. Setting multiple values in either group — multiple "state..." values, for example &mdash has undefined results. Individual values are separated by a vertical bar (|). For example:

<activity android:windowSoftInputMode="stateVisible|adjustResize" . . . >

Values set here (other than "stateUnspecified" and "adjustUnspecified") override values set in the theme.

Value Description
"stateUnspecified" The state of the soft keyboard (whether it is hidden or visible) is not specified. The system will choose an appropriate state or rely on the setting in the theme.

This is the default setting for the behavior of the soft keyboard.

"stateUnchanged" The soft keyboard is kept in whatever state it was last in, whether visible or hidden, when the activity comes to the fore.
"stateHidden" The soft keyboard is hidden when the user chooses the activity — that is, when the user affirmatively navigates forward to the activity, rather than backs into it because of leaving another activity.
"stateAlwaysHidden" The soft keyboard is always hidden when the activity's main window has input focus.
"stateVisible" The soft keyboard is visible when that's normally appropriate (when the user is navigating forward to the activity's main window).
"stateAlwaysVisible" The soft keyboard is made visible when the user chooses the activity — that is, when the user affirmatively navigates forward to the activity, rather than backs into it because of leaving another activity.
"adjustUnspecified" It is unspecified whether the activity's main window resizes to make room for the soft keyboard, or whether the contents of the window pan to make the currentfocus visible on-screen. The system will automatically select one of these modes depending on whether the content of the window has any layout views that can scroll their contents. If there is such a view, the window will be resized, on the assumption that scrolling can make all of the window's contents visible within a smaller area.

This is the default setting for the behavior of the main window.

"adjustResize" The activity's main window is always resized to make room for the soft keyboard on screen.
"adjustPan" The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desireable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.

This attribute was introduced in API Level 3.

introduced in:
API Level 1 for all attributes except for noHistory and windowSoftInputMode, which were added in API Level 3.
see also:
<application>
<activity-alias>

'old > App' 카테고리의 다른 글

<action>__AndroidManifest.xml  (0) 2010.02.04
The AndroidManifest.xml File  (0) 2010.02.04
Application Fundamentals  (0) 2010.02.04
Posted by jazzlife
,

<action>

syntax:
<action android:name="string" />
contained in:
<intent-filter>
description:
Adds an action to an intent filter. An <intent-filter> element must contain one or more <action> elements. If it doesn't contain any, no 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.
attributes:
android:name
The name of the action. Some standard actions are defined in the Intent class as ACTION_string constants. To assign one of these actions to this attribute, prepend "android.intent.action." to the string that follows ACTION_. For example, for ACTION_MAIN, use "android.intent.action.MAIN" and for ACTION_WEB_SEARCH, use "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 TRANSMOGRIFY action might be specified as follows:

<action android:name="com.example.project.TRANSMOGRIFY" />
introduced in:
API Level 1
see also:
<intent-filter>

'old > App' 카테고리의 다른 글

<activity>__AndroidManifest.xml  (0) 2010.02.04
The AndroidManifest.xml File  (0) 2010.02.04
Application Fundamentals  (0) 2010.02.04
Posted by jazzlife
,

The AndroidManifest.xml File

Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code. Among other things, the manifest does the following:

  • It names the Java package for the application. The package name serves as a unique identifier for the application.
  • It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched.
  • It determines which processes will host application components.
  • It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.
  • It also declares the permissions that others are required to have in order to interact with the application's components.
  • It lists the Instrumentation classes that provide profiling and other information as the application is running. These declarations are present in the manifest only while the application is being developed and tested; they're removed before the application is published.
  • It declares the minimum level of the Android API that the application requires.
  • It lists the libraries that the application must be linked against.

Structure of the Manifest File

The diagram below shows the general structure of the manifest file and every element that it can contain. Each element, along with all of its attributes, is documented in full in a separate file. To view detailed information about any element, click on the element name in the diagram, in the alphabetical list of elements that follows the diagram, or on any other mention of the element name.

<?xml version="1.0" encoding="utf-8"?> 
 
<manifest> 
 
    <uses-permission /> 
    <permission /> 
    <permission-tree /> 
    <permission-group /> 
    <instrumentation /> 
    <uses-sdk /> 
    <uses-configuration />   
    <uses-feature />   
    <supports-screens />   
 
    <application> 
 
        <activity> 
            <intent-filter> 
                <action /> 
                <category /> 
                <data /> 
            </intent-filter> 
            <meta-data /> 
        </activity> 
 
        <activity-alias> 
            <intent-filter> . . . </intent-filter> 
            <meta-data /> 
        </activity-alias> 
 
        <service> 
            <intent-filter> . . . </intent-filter> 
            <meta-data/> 
        </service> 
 
        <receiver> 
            <intent-filter> . . . </intent-filter> 
            <meta-data /> 
        </receiver> 
 
        <provider> 
            <grant-uri-permission /> 
            <path-permission /> 
            <meta-data /> 
        </provider> 
 
        <uses-library /> 
 
    </application> 
 
</manifest>

All the elements that can appear in the manifest file are listed below in alphabetical order. These are the only legal elements; you cannot add your own elements or attributes.

<action>
<activity>
<activity-alias>
<application>
<category>
<data>
<grant-uri-permission>
<instrumentation>
<intent-filter>
<manifest>
<meta-data>
<path-permission />
<permission>
<permission-group>
<permission-tree>
<provider>
<receiver>
<service>
<supports-screens>
<uses-configuration>
<uses-feature>
<uses-library>
<uses-permission>
<uses-sdk>

File Conventions

Some conventions and rules apply generally to all elements and attributes in the manifest:

Elements
Only the <manifest> and <application> elements are required, they each must be present and can occur only once. Most of the others can occur many times or not at all — although at least some of them must be present for the manifest to accomplish anything meaningful.

If an element contains anything at all, it contains other elements. All values are set through attributes, not as character data within an element.

Elements at the same level are generally not ordered. For example, <activity>, <provider>, and <service> elements can be intermixed in any sequence. (An <activity-alias> element is the exception to this rule: It must follow the <activity> it is an alias for.)

Attributes
In a formal sense, all attributes are optional. However, there are some that must be specified for an element to accomplish its purpose. Use the documentation as a guide. For truly optional attributes, it mentions a default value or states what happens in the absence of a specification.

Except for some attributes of the root <manifest> element, all attribute names begin with an android: prefix — for example, android:alwaysRetainTaskState. Because the prefix is universal, the documentation generally omits it when referring to attributes by name.

Declaring class names
Many elements correspond to Java objects, including elements for the application itself (the <application> element) and its principal components — activities (<activity>), services (<service>), broadcast receivers (<receiver>), and content providers (<provider>).

If you define a subclass, as you almost always would for the component classes (Activity, Service, BroadcastReceiver, and ContentProvider), the subclass is declared through a name attribute. The name must include the full package designation. For example, an Service subclass might be declared as follows:

<manifest . . . > 
    <application . . . > 
        <service android:name="com.example.project.SecretService" . . . > 
            . . . 
        </service> 
        . . . 
    </application> 
</manifest>

However, as a shorthand, if the first character of the string is a period, the string is appended to the application's package name (as specified by the <manifest> element's package attribute). The following assignment is the same as the one above:

<manifest package="com.example.project" . . . > 
    <application . . . > 
        <service android:name=".SecretService" . . . > 
            . . . 
        </service> 
        . . . 
    </application> 
</manifest>

When starting a component, Android creates an instance of the named subclass. If a subclass isn't specified, it creates an instance of the base class.

Multiple values
If more than one value can be specified, the element is almost always repeated, rather than listing multiple values within a single element. For example, an intent filter can list several actions:
<intent-filter . . . > 
    <action android:name="android.intent.action.EDIT" /> 
    <action android:name="android.intent.action.INSERT" /> 
    <action android:name="android.intent.action.DELETE" /> 
    . . . 
</intent-filter>
Resource values
Some attributes have values that can be displayed to users — for example, a label and an icon for an activity. The values of these attributes should be localized and therefore set from a resource or theme. Resource values are expressed in the following format,

@[package:]type:name

where the package name can be omitted if the resource is in the same package as the application, type is a type of resource — such as "string" or "drawable" — and name is the name that identifies the specific resource. For example:

<activity android:icon="@drawable/smallPic" . . . >

Values from a theme are expressed in a similar manner, but with an initial '?' rather than '@':

?[package:]type:name

String values
Where an attribute value is a string, double backslashes ('\\') must be used to escape characters — for example, '\\n' for a newline or '\\uxxxx' for a Unicode character.

File Features

The following sections describe how some Android features are reflected in the manifest file.

Intent Filters

The core components of an application (its activities, services, and broadcast receivers) are activated by intents. An intent is a bundle of information (an Intent object) describing a desired action — including the data to be acted upon, the category of component that should perform the action, and other pertinent instructions. Android locates an appropriate component to respond to the intent, launches a new instance of the component if one is needed, and passes it the Intent object.

Components advertise their capabilities — the kinds of intents they can respond to — through intent filters. Since the Android system must learn which intents a component can handle before it launches the component, intent filters are specified in the manifest as <intent-filter> elements. A component may have any number of filters, each one describing a different capability.

An intent that explicitly names a target component will activate that component; the filter doesn't play a role. But an intent that doesn't specify a target by name can activate a component only if it can pass through one of the component's filters.

For information on how Intent objects are tested against intent filters, see a separate document, Intents and Intent Filters.

Icons and Labels

A number of elements have icon and label attributes for a small icon and a text label that can be displayed to users. Some also have a description attribute for longer explanatory text that can also be shown on-screen. For example, the <permission> element has all three of these attributes, so that when the user is asked whether to grant the permission to an application that has requested it, an icon representing the permission, the name of the permission, and a description of what it entails can all be presented to the user.

In every case, the icon and label set in a containing element become the default icon and label settings for all of the container's subelements. Thus, the icon and label set in the <application> element are the default icon and label for each of the application's components. Similarly, the icon and label set for a component — for example, an <activity> element — are the default settings for each of the component's <intent-filter> elements. If an <application> element sets a label, but an activity and its intent filter do not, the application label is treated as the label for both the activity and the intent filter.

The icon and label set for an intent filter are used to represent a component whenever the component is presented to the user as fulfilling the function advertised by the filter. For example, a filter with "android.intent.action.MAIN" and "android.intent.category.LAUNCHER" settings advertises an activity as one that initiates an application — that is, as one that should be displayed in the application launcher. The icon and label set in the filter are therefore the ones displayed in the launcher.

Permissions

A permission is a restriction limiting access to a part of the code or to data on the device. The limitation is imposed to protect critical data and code that could be misused to distort or damage the user experience.

Each permission is identified by a unique label. Often the label indicates the action that's restricted. For example, here are some permissions defined by Android:

android.permission.CALL_EMERGENCY_NUMBERS
android.permission.READ_OWNER_DATA
android.permission.SET_WALLPAPER
android.permission.DEVICE_POWER

A feature can be protected by at most one permission.

If an application needs access to a feature protected by a permission, it must declare that it requires that permission with a <uses-permission> element in the manifest. Then, when the application is installed on the device, the installer determines whether or not to grant the requested permission by checking the authorities that signed the application's certificates and, in some cases, asking the user. If the permission is granted, the application is able to use the protected features. If not, its attempts to access those features will simply fail without any notification to the user.

An application can also protect its own components (activities, services, broadcast receivers, and content providers) with permissions. It can employ any of the permissions defined by Android (listed in android.Manifest.permission) or declared by other applications. Or it can define its own. A new permission is declared with the <permission> element. For example, an activity could be protected as follows:

<manifest . . . > 
    <permission android:name="com.example.project.DEBIT_ACCT" . . . /> 
    . . . 
    <application . . .> 
        <activity android:name="com.example.project.FreneticActivity" 
                  android:permission="com.example.project.DEBIT_ACCT" 
                  . . . > 
            . . . 
        </activity> 
    </application> 
    . . . 
    <uses-permission android:name="com.example.project.DEBIT_ACCT" /> 
    . . . 
</manifest>

Note that, in this example, the DEBIT_ACCT permission is not only declared with the <permission> element, its use is also requested with the <uses-permission> element. Its use must be requested in order for other components of the application to launch the protected activity, even though the protection is imposed by the application itself.

If, in the same example, the permission attribute was set to a permission declared elsewhere (such as android.permission.CALL_EMERGENCY_NUMBERS, it would not have been necessary to declare it again with a <permission> element. However, it would still have been necessary to request its use with <uses-permission>.

The <permission-tree> element declares a namespace for a group of permissions that will be defined in code. And <permission-group> defines a label for a set of permissions (both those declared in the manifest with <permission> elements and those declared elsewhere). It affects only how the permissions are grouped when presented to the user. The <permission-group> element does not specify which permissions belong to the group; it just gives the group a name. A permission is placed in the group by assigning the group name to the <permission> element's permissionGroup attribute.

Libraries

Every application is linked against the default Android library, which includes the basic packages for building applications (with common classes such as Activity, Service, Intent, View, Button, Application, ContentProvider, and so on).

However, some packages reside in their own libraries. If your application uses code from any of these packages, it must explicitly asked to be linked against them. The manifest must contain a separate <uses-library> element to name each of the libraries. (The library name can be found in the documentation for the package.)

'old > App' 카테고리의 다른 글

<activity>__AndroidManifest.xml  (0) 2010.02.04
<action>__AndroidManifest.xml  (0) 2010.02.04
Application Fundamentals  (0) 2010.02.04
Posted by jazzlife
,

Application Fundamentals

old/App 2010. 2. 4. 20:24

Application Fundamentals

Android applications are written in the Java programming language. The compiled Java code — along with any data and resource files required by the application — is bundled by the aapt tool into an Android package, an archive file marked by an .apk suffix. This file is the vehicle for distributing the application and installing it on mobile devices; it's the file users download to their devices. All the code in a single .apk file is considered to be one application.

In many ways, each Android application lives in its own world:

  • By default, every application runs in its own Linux process. Android starts the process when any of the application's code needs to be executed, and shuts down the process when it's no longer needed and system resources are required by other applications.
  • Each process has its own Java virtual machine (VM), so application code runs in isolation from the code of all other applications.
  • By default, each application is assigned a unique Linux user ID. Permissions are set so that the application's files are visible only that user, only to the application itself — although there are ways to export them to other applications as well.

It's possible to arrange for two applications to share the same user ID, in which case they will be able to see each other's files. To conserve system resources, applications with the same ID can also arrange to run in the same Linux process, sharing the same VM.

Application Components

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.

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

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:

  • 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

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>

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.

Activities and Tasks

As noted earlier, one activity can start another, including one defined in a different application. Suppose, for example, that you'd like to let users display a street map of some location. There's already an activity that can do that, so all your activity needs to do is put together an Intent object with the required information and pass it to startActivity(). The map viewer will display the map. When the user hits the BACK key, your activity will reappear on screen.

To the user, it will seem as if the map viewer is part of the same application as your activity, even though it's defined in another application and runs in that application's process. Android maintains this user experience by keeping both activities in the same task. Simply put, a task is what the user experiences as an "application." It's a group of related activities, arranged in a stack. The root activity in the stack is the one that began the task — typically, it's an activity the user selected in the application launcher. The activity at the top of the stack is one that's currently running — the one that is the focus for user actions. When one activity starts another, the new activity is pushed on the stack; it becomes the running activity. The previous activity remains in the stack. When the user presses the BACK key, the current activity is popped from the stack, and the previous one resumes as the running activity.

The stack contains objects, so if a task has more than one instance of the same Activity subclass open — multiple map viewers, for example — the stack has a separate entry for each instance. Activities in the stack are never rearranged, only pushed and popped.

A task is a stack of activities, not a class or an element in the manifest file. So there's no way to set values for a task independently of its activities. Values for the task as a whole are set in the root activity. For example, the next section will talk about the "affinity of a task"; that value is read from the affinity set for the task's root activity.

All the activities in a task move together as a unit. The entire task (the entire activity stack) can be brought to the foreground or sent to the background. Suppose, for instance, that the current task has four activities in its stack — three under the current activity. The user presses the HOME key, goes to the application launcher, and selects a new application (actually, a new task). The current task goes into the background and the root activity for the new task is displayed. Then, after a short period, the user goes back to the home screen and again selects the previous application (the previous task). That task, with all four activities in the stack, comes forward. When the user presses the BACK key, the screen does not display the activity the user just left (the root activity of the previous task). Rather, the activity on the top of the stack is removed and the previous activity in the same task is displayed.

The behavior just described is the default behavior for activities and tasks. But there are ways to modify almost all aspects of it. The association of activities with tasks, and the behavior of an activity within a task, is controlled by the interaction between flags set in the Intent object that started the activity and attributes set in the activity's <activity> element in the manifest. Both requester and respondent have a say in what happens.

In this regard, the principal Intent flags are:

FLAG_ACTIVITY_NEW_TASK
FLAG_ACTIVITY_CLEAR_TOP
FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
FLAG_ACTIVITY_SINGLE_TOP

The principal <activity> attributes are:

taskAffinity
launchMode
allowTaskReparenting
clearTaskOnLaunch
alwaysRetainTaskState
finishOnTaskLaunch

The following sections describe what some of these flags and attributes do, how they interact, and what considerations should govern their use.

Affinities and new tasks

By default, all the activities in an application have an affinity for each other — that is, there's a preference for them all to belong to the same task. However, an individual affinity can be set for each activity with the taskAffinity attribute of the <activity> element. Activities defined in different applications can share an affinity, or activities defined in the same application can be assigned different affinities. The affinity comes into play in two circumstances: When the Intent object that launches an activity contains the FLAG_ACTIVITY_NEW_TASK flag, and when an activity has its allowTaskReparenting attribute set to "true".

The FLAG_ACTIVITY_NEW_TASK flag
As described earlier, a new activity is, by default, launched into the task of the activity that called startActivity(). It's pushed onto the same stack as the caller. However, if the Intent object passed to startActivity() contains the FLAG_ACTIVITY_NEW_TASK flag, the system looks for a different task to house the new activity. Often, as the name of the flag implies, it's a new task. However, it doesn't have to be. If there's already an existing task with the same affinity as the new activity, the activity is launched into that task. If not, it begins a new task.
The allowTaskReparenting attribute
If an activity has its allowTaskReparenting attribute set to "true", it can move from the task it starts in to the task it has an affinity for when that task comes to the fore. For example, suppose that an activity that reports weather conditions in selected cities is defined as part of a travel application. It has the same affinity as other activities in the same application (the default affinity) and it allows reparenting. One of your activities starts the weather reporter, so it initially belongs to the same task as your activity. However, when the travel application next comes forward, the weather reporter will be reassigned to and displayed with that task.

If an .apk file contains more than one "application" from the user's point of view, you will probably want to assign different affinities to the activities associated with each of them.

Launch modes

There are four different launch modes that can be assigned to an <activity> element's launchMode attribute:

"standard" (the default mode)
"singleTop"
"singleTask"
"singleInstance"

The modes differ from each other on these four points:

  • Which task will hold the activity that responds to the intent. For the "standard" and "singleTop" modes, it's the task that originated the intent (and called startActivity()) — unless the Intent object contains the FLAG_ACTIVITY_NEW_TASK flag. In that case, a different task is chosen as described in the previous section, Affinities and new tasks.

    In contrast, the "singleTask" and "singleInstance" modes mark activities that are always at the root of a task. They define a task; they're never launched into another task.

  • Whether there can be multiple instances of the activity. A "standard" or "singleTop" activity can be instantiated many times. They can belong to multiple tasks, and a given task can have multiple instances of the same activity.

    In contrast, "singleTask" and "singleInstance" activities are limited to just one instance. Since these activities are at the root of a task, this limitation means that there is never more than a single instance of the task on the device at one time.

  • Whether the instance can have other activities in its task. A "singleInstance" activity stands alone as the only activity in its task. If it starts another activity, that activity will be launched into a different task regardless of its launch mode — as if FLAG_ACTIVITY_NEW_TASK was in the intent. In all other respects, the "singleInstance" mode is identical to "singleTask".

    The other three modes permit multiple activities to belong to the task. A "singleTask" activity will always be the root activity of the task, but it can start other activities that will be assigned to its task. Instances of "standard" and "singleTop" activities can appear anywhere in a stack.

  • Whether a new instance of the class will be launched to handle a new intent. For the default "standard" mode, a new instance is created to respond to every new intent. Each instance handles just one intent. For the "singleTop" mode, an existing instance of the class is re-used to handle a new intent if it resides at the top of the activity stack of the target task. If it does not reside at the top, it is not re-used. Instead, a new instance is created for the new intent and pushed on the stack.

    For example, suppose a task's activity stack consists of root activity A with activities B, C, and D on top in that order, so the stack is A-B-C-D. An intent arrives for an activity of type D. If D has the default "standard" launch mode, a new instance of the class is launched and the stack becomes A-B-C-D-D. However, if D's launch mode is "singleTop", the existing instance is expected to handle the new intent (since it's at the top of the stack) and the stack remains A-B-C-D.

    If, on the other hand, the arriving intent is for an activity of type B, a new instance of B would be launched no matter whether B's mode is "standard" or "singleTop" (since B is not at the top of the stack), so the resulting stack would be A-B-C-D-B.

    As noted above, there's never more than one instance of a "singleTask" or "singleInstance" activity, so that instance is expected to handle all new intents. A "singleInstance" activity is always at the top of the stack (since it is the only activity in the task), so it is always in position to handle the intent. However, a "singleTask" activity may or may not have other activities above it in the stack. If it does, it is not in position to handle the intent, and the intent is dropped. (Even though the intent is dropped, its arrival would have caused the task to come to the foreground, where it would remain.)

When an existing activity is asked to handle a new intent, the Intent object is passed to the activity in an onNewIntent() call. (The intent object that originally started the activity can be retrieved by calling getIntent().)

Note that when a new instance of an Activity is created to handle a new intent, the user can always press the BACK key to return to the previous state (to the previous activity). But when an existing instance of an Activity handles a new intent, the user cannot press the BACK key to return to what that instance was doing before the new intent arrived.

For more on launch modes, see the description of the <activity> element.

Clearing the stack

If the user leaves a task for a long time, the system clears the task of all activities except the root activity. When the user returns to the task again, it's as the user left it, except that only the initial activity is present. The idea is that, after a time, users will likely have abandoned what they were doing before and are returning to the task to begin something new.

That's the default. There are some activity attributes that can be used to control this behavior and modify it:

The alwaysRetainTaskState attribute
If this attribute is set to "true" in the root activity of a task, the default behavior just described does not happen. The task retains all activities in its stack even after a long period.
The clearTaskOnLaunch attribute
If this attribute is set to "true" in the root activity of a task, the stack is cleared down to the root activity whenever the user leaves the task and returns to it. In other words, it's the polar opposite of alwaysRetainTaskState. The user always returns to the task in its initial state, even after a momentary absence.
The finishOnTaskLaunch attribute
This attribute is like clearTaskOnLaunch, but it operates on a single activity, not an entire task. And it can cause any activity to go away, including the root activity. When it's set to "true", the activity remains part of the task only for the current session. If the user leaves and then returns to the task, it no longer is present.

There's another way to force activities to be removed from the stack. If an Intent object includes the FLAG_ACTIVITY_CLEAR_TOP flag, and the target task already has an instance of the type of activity that should handle the intent in its stack, all activities above that instance are cleared away so that it stands at the top of the stack and can respond to the intent. If the launch mode of the designated activity is "standard", it too will be removed from the stack, and a new instance will be launched to handle the incoming intent. That's because a new instance is always created for a new intent when the launch mode is "standard".

FLAG_ACTIVITY_CLEAR_TOP is most often used in conjunction with FLAG_ACTIVITY_NEW_TASK. When used together, these flags are a way of locating an existing activity in another task and putting it in a position where it can respond to the intent.

Starting tasks

An activity is set up as the entry point for a task by giving it an intent filter with "android.intent.action.MAIN" as the specified action and "android.intent.category.LAUNCHER" as the specified category. (There's an example of this type of filter in the earlier Intent Filters section.) A filter of this kind causes an icon and label for the activity to be displayed in the application launcher, giving users a way both to launch the task and to return to it at any time after it has been launched.

This second ability is important: Users must be able to leave a task and then come back to it later. For this reason, the two launch modes that mark activities as always initiating a task, "singleTask" and "singleInstance", should be used only when the activity has a MAIN and LAUNCHER filter. Imagine, for example, what could happen if the filter is missing: An intent launches a "singleTask" activity, initiating a new task, and the user spends some time working in that task. The user then presses the HOME key. The task is now ordered behind and obscured by the home screen. And, because it is not represented in the application launcher, the user has no way to return to it.

A similar difficulty attends the FLAG_ACTIVITY_NEW_TASK flag. If this flag causes an activity to begin a new task and the user presses the HOME key to leave it, there must be some way for the user to navigate back to it again. Some entities (such as the notification manager) always start activities in an external task, never as part of their own, so they always put FLAG_ACTIVITY_NEW_TASK in the intents they pass to startActivity(). If you have an activity that can be invoked by an external entity that might use this flag, take care that the user has a independent way to get back to the task that's started.

For those cases where you don't want the user to be able to return to an activity, set the <activity> element's finishOnTaskLaunch to "true". See Clearing the stack, earlier.

Processes and Threads

When the first of an application's components needs to be run, Android starts a Linux process for it with a single thread of execution. By default, all components of the application run in that process and thread.

However, you can arrange for components to run in other processes, and you can spawn additional threads for any process.

Processes

The process where a component runs is controlled by the manifest file. The component elements — <activity>, <service>, <receiver>, and <provider> — each have a process attribute that can specify a process where that component should run. These attributes can be set so that each component runs in its own process, or so that some components share a process while others do not. They can also be set so that components of different applications run in the same process — provided that the applications share the same Linux user ID and are signed by the same authorities. The <application> element also has a process attribute, for setting a default value that applies to all components.

All components are instantiated in the main thread of the specified process, and system calls to the component are dispatched from that thread. Separate threads are not created for each instance. Consequently, methods that respond to those calls — methods like View.onKeyDown() that report user actions and the lifecycle notifications discussed later in the Component Lifecycles section — always run in the main thread of the process. This means that no component should perform long or blocking operations (such as networking operations or computation loops) when called by the system, since this will block any other components also in the process. You can spawn separate threads for long operations, as discussed under Threads, next.

Android may decide to shut down a process at some point, when memory is low and required by other processes that are more immediately serving the user. Application components running in the process are consequently destroyed. A process is restarted for those components when there's again work for them to do.

When deciding which processes to terminate, Android weighs their relative importance to the user. For example, it more readily shuts down a process with activities that are no longer visible on screen than a process with visible activities. The decision whether to terminate a process, therefore, depends on the state of the components running in that process. Those states are the subject of a later section, Component Lifecycles.

Threads

Even though you may confine your application to a single process, there will likely be times when you will need to spawn a thread to do some background work. Since the user interface must always be quick to respond to user actions, the thread that hosts an activity should not also host time-consuming operations like network downloads. Anything that may not be completed quickly should be assigned to a different thread.

Threads are created in code using standard Java Thread objects. Android provides a number of convenience classes for managing threads — Looper for running a message loop within a thread, Handler for processing messages, and HandlerThread for setting up a thread with a message loop.

Remote procedure calls

Android has a lightweight mechanism for remote procedure calls (RPCs) — where a method is called locally, but executed remotely (in another process), with any result returned back to the caller. This entails decomposing the method call and all its attendant data to a level the operating system can understand, transmitting it from the local process and address space to the remote process and address space, and reassembling and reenacting the call there. Return values have to be transmitted in the opposite direction. Android provides all the code to do that work, so that you can concentrate on defining and implementing the RPC interface itself.

An RPC interface can include only methods. All methods are executed synchronously (the local method blocks until the remote method finishes), even if there is no return value.

In brief, the mechanism works as follows: You'd begin by declaring the RPC interface you want to implement using a simple IDL (interface definition language). From that declaration, the aidl tool generates a Java interface definition that must be made available to both the local and the remote process. It contains two inner class, as shown in the following diagram:

RPC mechanism.

The inner classes have all the code needed to administer remote procedure calls for the interface you declared with the IDL. Both inner classes implement the IBinder interface. One of them is used locally and internally by the system; the code you write can ignore it. The other, called Stub, extends the Binder class. In addition to internal code for effectuating the IPC calls, it contains declarations for the methods in the RPC interface you declared. You would subclass Stub to implement those methods, as indicated in the diagram.

Typically, the remote process would be managed by a service (because a service can inform the system about the process and its connections to other processes). It would have both the interface file generated by the aidl tool and the Stub subclass implementing the RPC methods. Clients of the service would have only the interface file generated by the aidl tool.

Here's how a connection between a service and its clients is set up:

  • Clients of the service (on the local side) would implement onServiceConnected() and onServiceDisconnected() methods so they can be notified when a successful connection to the remote service is established, and when it goes away. They would then call bindService() to set up the connection.
  • The service's onBind() method would be implemented to either accept or reject the connection, depending on the intent it receives (the intent passed to bindService()). If the connection is accepted, it returns an instance of the Stub subclass.
  • If the service accepts the connection, Android calls the client's onServiceConnected() method and passes it an IBinder object, a proxy for the Stub subclass managed by the service. Through the proxy, the client can make calls on the remote service.

This brief description omits some details of the RPC mechanism. For more information, see Designing a Remote Interface Using AIDL and the IBinder class description.

Thread-safe methods

In a few contexts, the methods you implement may be called from more than one thread, and therefore must be written to be thread-safe.

This is primarily true for methods that can be called remotely — as in the RPC mechanism discussed in the previous section. When a call on a method implemented in an IBinder object originates in the same process as the IBinder, the method is executed in the caller's thread. However, when the call originates in another process, the method is executed in a thread chosen from a pool of threads that Android maintains in the same process as the IBinder; it's not executed in the main thread of the process. For example, whereas a service's onBind() method would be called from the main thread of the service's process, methods implemented in the object that onBind() returns (for example, a Stub subclass that implements RPC methods) would be called from threads in the pool. Since services can have more than one client, more than one pool thread can engage the same IBinder method at the same time. IBinder methods must, therefore, be implemented to be thread-safe.

Similarly, a content provider can receive data requests that originate in other processes. Although the ContentResolver and ContentProvider classes hide the details of how the interprocess communication is managed, ContentProvider methods that respond to those requests — the methods query(), insert(), delete(), update(), and getType() — are called from a pool of threads in the content provider's process, not the main thread of the process. Since these methods may be called from any number of threads at the same time, they too must be implemented to be thread-safe.

Component Lifecycles

Application components have a lifecycle — a beginning when Android instantiates them to respond to intents through to an end when the instances are destroyed. In between, they may sometimes be active or inactive,or, in the case of activities, visible to the user or invisible. This section discusses the lifecycles of activities, services, and broadcast receivers — including the states that they can be in during their lifetimes, the methods that notify you of transitions between states, and the effect of those states on the possibility that the process hosting them might be terminated and the instances destroyed.

Activity lifecycle

An activity has essentially three states:

  • It is active or running when it is in the foreground of the screen (at the top of the activity stack for the current task). This is the activity that is the focus for the user's actions.
  • It is paused if it has lost focus but is still visible to the user. That is, another activity lies on top of it and that activity either is transparent or doesn't cover the full screen, so some of the paused activity can show through. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.

  • It is stopped if it is completely obscured by another activity. It still retains all state and member information. However, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.

If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its finish() method), or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

As an activity transitions from state to state, it is notified of the change by calls to the following protected methods:

void onCreate(Bundle savedInstanceState)
void onStart()
void onRestart()
void onResume()
void onPause()
void onStop()
void onDestroy()

All of these methods are hooks that you can override to do appropriate work when the state changes. All activities must implement onCreate() to do the initial setup when the object is first instantiated. Many will also implement onPause() to commit data changes and otherwise prepare to stop interacting with the user.

Taken together, these seven methods define the entire lifecycle of an activity. There are three nested loops that you can monitor by implementing them:

  • The entire lifetime of an activity happens between the first call to onCreate() through to a single final call to onDestroy(). An activity does all its initial setup of "global" state in onCreate(), and releases all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().
  • The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time, the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user can no longer see what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity alternates between being visible and hidden to the user.

  • The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time, the activity is in front of all other activities on screen and is interacting with the user. An activity can frequently transition between the resumed and paused states — for example, onPause() is called when the device goes to sleep or when a new activity is started, onResume() is called when an activity result or a new intent is delivered. Therefore, the code in these two methods should be fairly lightweight.

The following diagram illustrates these loops and the paths an activity may take between states. The colored ovals are major states the activity can be in. The square rectangles represent the callback methods you can implement to perform operations when the activity transitions between states.

State diagram for an Android activity lifecycle.

The following table describes each of these methods in more detail and locates it within the activity's overall lifecycle:

Method Description Killable? Next
onCreate() Called when the activity is first created. This is where you should do all of your normal static set up — create views, bind data to lists, and so on. This method is passed a Bundle object containing the activity's previous state, if that state was captured (see Saving Activity State, later).

Always followed by onStart().

No onStart()
    onRestart() Called after the activity has been stopped, just prior to it being started again.

Always followed by onStart()

No onStart()
onStart() Called just before the activity becomes visible to the user.

Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

No onResume()
or
onStop()
    onResume() Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it.

Always followed by onPause().

No onPause()
onPause() Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns.

Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user.

Yes onResume()
or
onStop()
onStop() Called when the activity is no longer visible to the user. This may happen because it is being destroyed, or because another activity (either an existing one or a new one) has been resumed and is covering it.

Followed either by onRestart() if the activity is coming back to interact with the user, or by onDestroy() if this activity is going away.

Yes onRestart()
or
onDestroy()
onDestroy() Called before the activity is destroyed. This is the final call that the activity will receive. It could be called either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method. Yes nothing

Note the Killable column in the table above. It indicates whether or not the system can kill the process hosting the activity at any time after the method returns, without executing another line of the activity's code. Three methods (onPause(), onStop(), and onDestroy()) are marked "Yes." Because onPause() is the first of the three, it's the only one that's guaranteed to be called before the process is killed — onStop() and onDestroy() may not be. Therefore, you should use onPause() to write any persistent data (such as user edits) to storage.

Methods that are marked "No" in the Killable column protect the process hosting the activity from being killed from the moment they are called. Thus an activity is in a killable state, for example, from the time onPause() returns to the time onResume() is called. It will not again be killable until onPause() again returns.

As noted in a later section, Processes and lifecycle, an activity that's not technically "killable" by this definition might still be killed by the system — but that would happen only in extreme and dire circumstances when there is no other recourse.

Saving activity state

When the system, rather than the user, shuts down an activity to conserve memory, the user may expect to return to the activity and find it in its previous state.

To capture that state before the activity is killed, you can implement an onSaveInstanceState() method for the activity. Android calls this method before making the activity vulnerable to being destroyed — that is, before onPause() is called. It passes the method a Bundle object where you can record the dynamic state of the activity as name-value pairs. When the activity is again started, the Bundle is passed both to onCreate() and to a method that's called after onStart(), onRestoreInstanceState(), so that either or both of them can recreate the captured state.

Unlike onPause() and the other methods discussed earlier, onSaveInstanceState() and onRestoreInstanceState() are not lifecycle methods. They are not always called. For example, Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key). In that case, the user won't expect to return to the activity, so there's no reason to save its state.

Because onSaveInstanceState() is not always called, you should use it only to record the transient state of the activity, not to store persistent data. Use onPause() for that purpose instead.

Coordinating activities

When one activity starts another, they both experience lifecycle transitions. One pauses and may stop, while the other starts up. On occasion, you may need to coordinate these activities, one with the other.

The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process:

  1. The current activity's onPause() method is called.
  2. Next, the starting activity's onCreate(), onStart(), and onResume() methods are called in sequence.
  3. Then, if the starting activity is no longer visible on screen, its onStop() method is called.

Service lifecycle

A service can be used in two ways:

  • It can be started and allowed to run until someone stops it or it stops itself. In this mode, it's started by calling Context.startService() and stopped by calling Context.stopService(). It can stop itself by calling Service.stopSelf() or Service.stopSelfResult(). Only one stopService() call is needed to stop the service, no matter how many times startService() was called.
  • It can be operated programmatically using an interface that it defines and exports. Clients establish a connection to the Service object and use that connection to call into the service. The connection is established by calling Context.bindService(), and is closed by calling Context.unbindService(). Multiple clients can bind to the same service. If the service has not already been launched, bindService() can optionally launch it.

The two modes are not entirely separate. You can bind to a service that was started with startService(). For example, a background music service could be started by calling startService() with an Intent object that identifies the music to play. Only later, possibly when the user wants to exercise some control over the player or get information about the current song, would an activity establish a connection to the service by calling bindService(). In cases like this, stopService() will not actually stop the service until the last binding is closed.

Like an activity, a service has lifecycle methods that you can implement to monitor changes in its state. But they are fewer than the activity methods — only three — and they are public, not protected:

void onCreate()
void onStart(Intent intent)
void onDestroy()

By implementing these methods, you can monitor two nested loops of the service's lifecycle:

  • The entire lifetime of a service happens between the time onCreate() is called and the time onDestroy() returns. Like an activity, a service does its initial setup in onCreate(), and releases all remaining resources in onDestroy(). For example, a music playback service could create the thread where the music will be played in onCreate(), and then stop the thread in onDestroy().
  • The active lifetime of a service begins with a call to onStart(). This method is handed the Intent object that was passed to startService(). The music service would open the Intent to discover which music to play, and begin the playback.

    There's no equivalent callback for when the service stops — no onStop() method.

The onCreate() and onDestroy() methods are called for all services, whether they're started by Context.startService() or Context.bindService(). However, onStart() is called only for services started by startService().

If a service permits others to bind to it, there are additional callback methods for it to implement:

IBinder onBind(Intent intent)
boolean onUnbind(Intent intent)
void onRebind(Intent intent)

The onBind() callback is passed the Intent object that was passed to bindService and onUnbind() is handed the intent that was passed to unbindService(). If the service permits the binding, onBind() returns the communications channel that clients use to interact with the service. The onUnbind() method can ask for onRebind() to be called if a new client connects to the service.

The following diagram illustrates the callback methods for a service. Although, it separates services that are created via startService from those created by bindService(), keep in mind that any service, no matter how it's started, can potentially allow clients to bind to it, so any service may receive onBind() and onUnbind() calls.

State diagram for Service callbacks.

Broadcast receiver lifecycle

A broadcast receiver has single callback method:

void onReceive(Context curContext, Intent broadcastMsg)

When a broadcast message arrives for the receiver, Android calls its onReceive() method and passes it the Intent object containing the message. The broadcast receiver is considered to be active only while it is executing this method. When onReceive() returns, it is inactive.

A process with an active broadcast receiver is protected from being killed. But a process with only inactive components can be killed by the system at any time, when the memory it consumes is needed by other processes.

This presents a problem when the response to a broadcast message is time consuming and, therefore, something that should be done in a separate thread, away from the main thread where other components of the user interface run. If onReceive() spawns the thread and then returns, the entire process, including the new thread, is judged to be inactive (unless other application components are active in the process), putting it in jeopardy of being killed. The solution to this problem is for onReceive() to start a service and let the service do the job, so the system knows that there is still active work being done in the process.

The next section has more on the vulnerability of processes to being killed.

Processes and lifecycles

The Android system tries to maintain an application process for as long as possible, but eventually it will need to remove old processes when memory runs low. To determine which processes to keep and which to kill, Android places each process into an "importance hierarchy" based on the components running in it and the state of those components. Processes with the lowest importance are eliminated first, then those with the next lowest, and so on. There are five levels in the hierarchy. The following list presents them in order of importance:

  1. A foreground process is one that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions hold:
    • It is running an activity that the user is interacting with (the Activity object's onResume() method has been called).
    • It hosts a service that's bound to the activity that the user is interacting with.

    • It has a Service object that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).

    • It has a BroadcastReceiver object that's executing its onReceive() method.

    Only a few foreground processes will exist at any given time. They are killed only as a last resort — if memory is so low that they cannot all continue to run. Generally, at that point, the device has reached a memory paging state, so killing some foreground processes is required to keep the user interface responsive.

  2. A visible process is one that doesn't have any foreground components, but still can affect what the user sees on screen. A process is considered to be visible if either of the following conditions holds:

    • It hosts an activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This may occur, for example, if the foreground activity is a dialog that allows the previous activity to be seen behind it.
    • It hosts a service that's bound to a visible activity.

    A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running.

  3. A service process is one that is running a service that has been started with the startService() method and that does not fall into either of the two higher categories. Although service processes are not directly tied to anything the user sees, they are generally doing things that the user cares about (such as playing an mp3 in the background or downloading data on the network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes.

  4. A background process is one holding an activity that's not currently visible to the user (the Activity object's onStop() method has been called). These processes have no direct impact on the user experience, and can be killed at any time to reclaim memory for a foreground, visible, or service process. Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and captures its current state, killing its process will not have a deleterious effect on the user experience.

  5. An empty process is one that doesn't hold any active application components. The only reason to keep such a process around is as a cache to improve startup time the next time a component needs to run in it. The system often kills these processes in order to balance overall system resources between process caches and the underlying kernel caches.

Android ranks a process at the highest level it can, based upon the importance of the components currently active in the process. For example, if a process hosts a service and a visible activity, the process will be ranked as a visible process, not a service process.

In addition, a process's ranking may be increased because other processes are dependent on it. A process that is serving another process can never be ranked lower than the process it is serving. For example, if a content provider in process A is serving a client in process B, or if a service in process A is bound to a component in process B, process A will always be considered at least as important as process B.

Because a process running a service is ranked higher than one with background activities, an activity that initiates a long-running operation might do well to start a service for that operation, rather than simply spawn a thread — particularly if the operation will likely outlast the activity. Examples of this are playing music in the background and uploading a picture taken by the camera to a web site. Using a service guarantees that the operation will have at least "service process" priority, regardless of what happens to the activity. As noted in the Broadcast receiver lifecycle section earlier, this is the same reason that broadcast receivers should employ services rather than simply put time-consuming operations in a thread.

'old > App' 카테고리의 다른 글

<activity>__AndroidManifest.xml  (0) 2010.02.04
<action>__AndroidManifest.xml  (0) 2010.02.04
The AndroidManifest.xml File  (0) 2010.02.04
Posted by jazzlife
,