이 명령어를 치면, Repos 선택하는 화면이 두개 뜬다. 첫화면은 세개 다 선택해주고, 두번째 화면에서는 맘에드는 걸로 하나씩 선택해보면서, pkg update 실행하면서 네트워크 오류가 안나는 Repository를 선택해주면 된다.
PKG update 하는 중에 화면이 멈춰 있는 걸 볼 수 있는데, Y/N 등을 할것인지 묻는 것 때문에 멈춰있다. (오류아님) 기존 버젼 유지할거라면 N, 유지보수버젼으로 설치할거라면 Y 누르면 된다. 입력없이 엔터를 치면 기본값은 N이 되니 참고하면 좋다.
...
한참 설치하다 보면, 암호 입력이 나온다. 사용자명 사용자암호 그리고 루트권한 암호 등
암호 입력창 완료 후
설치가 완료된 것처럼 보이지만, 암호를 입력해달라는 화면이니 그냥 끄면 안된다. 암호를 입력 후 남은 설치가 계속된다.
...
갑자기 이상한(?) 영어로 뭔가 선택하라고 한다. 시간대를 선택해 달라고 하는 화면이다. 당황하지 않고, 우리는 한국 사람이니, 'Asia'를 선택하고 다음화면에서 'Seoul'을 선택하면 된다.
...
또 무언가 뜬다. 잘 살펴보면, Keyboard라는 글자가 보인다. 자판 언어 선택해 달라고 하는 내용이다. 당황하지 않고, 우리는 한국 사람이니, Korea를 선택하고, 내 키보드는 Full-Key이니까 ( 텐키리스 아니니까. ) 일반 Korea로 선택해준다. [ 텐키리스 : 오른쪽에 3x3으로 넘버키가 없는 키보드를 흔히 텐키리스라고 함 ]
...
VNC Password 생성하기 위해 입력하라고 뜬다. 이 부분만 입력하면 드디어 설치가 끝난다.
화면 프롬프트에 xxxx@localhost라는 문구가 뜬다면 모두 완료된 것으로 보면 된다.
Unpack thepycharm-*.tar.gzfile to a different folder, if your currentDownloadfolder doesn't support file execution:The recommended installation location according to the filesystem hierarchy standard (FHS) is/opt. To install PyCharm into this directory, enter the following command:To verify integrity of the downloaded archive, use the SHA checksum linked from theDownloadpage.
sudo tar xzf pycharm-*.tar.gz -C /opt/
tar xzf pycharm-*.tar.gz -C <new_archive_folder>
Switch to thebinsubdirectory:For example,
cd /opt/pycharm-*/bin
cd <new archive folder>/pycharm-*/bin
Runpycharm.shfrom thebinsubdirectory.
sh pycharm.sh
pycharm.sh 설치 시 JRE 오류가 발생하면 아래와 같이 JRE를 설치 후 다시 하면 정상 완료됨
There are many ways to take a screen shot on Android device. One simple way to capture the screen on Galaxy Nexus is to simultaneously press and hold Power and Volume Down buttons. The image will be saved in a "Screenshot" directory and accessible via Gallery.
Quite often, however, I need to copy the captured image over to my computer. Usually, I do this with adb pull command, but if I'm going to use CLI to retrieve the file, why don't I take the screen shot with it as well?
One method is to use screencap command via adb shell like so:
Not bad, but seems like there's some room for improvement.
Information provided by screencap -h indicates that screen shot can be sent to stdout, but running adb shell screencap -p > screen.png results in seemingly corrupt file.
Luckily, I wasn't the first person looking into this issue. Apparently, adb shell is performing an EOL (end-of-line) character conversion, from LF (line feed, '\n', 0x0A) to CR+LF (carriage return followed by line feed, '\r\n', 0x0D0A).
If that sounds familiar, that's because I've dealt with this before. Unfortunately, this time we're working with binary data, so using tr -d '\r' command to remove all 0x0D will likely corrupt it by also removing bytes that aren't part of the 0x0D0A sequence. We want to only remove carriage return characters when they are followed by a line feed.
The solution is to use sed search and replace as follows:
adb shell screencap -p | sed 's/\r$//' > screen.png
Unfortunately, I found that sed fix while works on Ubuntu doesn't work on OS X. This solution using perl handles binary search and replace better:
Monkey는 Android SDK에서 제공하는 프로그램으로,emulator나 device에 대해 random한 event stream을 발생시킵니다. 마치 원숭이가 기기를 작동하는 것처럼 random event를 발생시키기 때문에 monkey라는 이름이 붙여졌습니다. Event는 click, touch, gesture, system level event 등이 있습니다.
2) 몽키 테스트의 목적.
Smart phone을 사용함에 있어,인간은 선행 학습에 의해 device와 상호작용을합니다.
따라서 극단적인 사용이나 Edge case 들에 대해 Error 가 발생하는지를 확인하기가 어렵습니다.
Ex)Android phone에 OK 버튼을 포함한 Pop up 메뉴가 나오면 인간은 OK 버튼을 클릭하지만, Monkey는 이를 인지하지 못하고 아무 버튼이나 누르거나 아무곳이나 터치하게 됩니다.
Monkey 의 경우randomevent stream을 발생시키기 때문에 예측불허인극단적인 상황도 테스트가 가능(Stress-test)하며, 프로그램 자체에서 event 발생 빈도, event 발생 주기, event 발생 횟수 등을 조절할 수 있기 때문에 human resource를 낭비하지 않고도 극단적인 상황을 쉽게 테스트 할 수 있습니다. Monkey test는보통 Application를 release 하기 전에 edge case들에 대한 저항성을 기르기 위해 합니다.
3) 몽키 테스트 사용 방법.
3-1) 기본 사용
Monkey test는 adb shell 환경에서 작동하는 어플리케이션입니다.
따라서, environment path가 지정되어 있지 않다면, android-sdk-windows\tools 에서
--pct-touch <percent> Touch event 발생 빈도 조절 --pct-motion <percent> 드래그 event 발생 빈도 조절 --pct-trackball <percent> 트랙볼 event 발생 빈도 조절 --pct-nav <percent> Navigation event 발생 빈도 조절 --pct-majornav <percent> Back, Home 버튼등의 major navigation event 발생 빈도 조절 --pct-syskeys <percent> System event 발생 빈도 조절 (Volume, home, end call 등) --pct-appswitch <percent> 새로운 app. 실행 event 발생 빈도 조절 --pct-anyevent <percent> 기타 event 발생 빈도 조절
Ex)..tools> adb shell monkey --pct-trackball 0 --pct-nav 0 --pct-touch 60 --pct-motion 20 ?v 500 : trackball, navigation 0%, touch 60%, motion 20%의 이벤트 비율로 event 500개 발생
3-3) 옵션 #2
Seed & Throttle & Times
-s <seed> Seed 설정 (Seed를 설정하지 않거나, 동일한 seed로 event를 발생시키면 항상 같은 event를 발생합니다.) --throttle <milliseconds> Event 사이의 delay 조정 -v <number of events> 설정한 수만큼의 event 발생
ADB 셸에서 Exerciser/Monkey 도구를 이용해서 특정 응용프로그램에 무작위한 사용자 사건들을 보낼 수 있다. Monkey라는 이름은 이 도구가 마치 단말기를 원숭이에게 넘겨준 후 마음대로 키를 누르거나 화면을 만지게 할 때와 비슷한 효과를 내기 때문에 붙은 것이다. 튼튼하게 설계되지 않았다면, 그런 무작위한 입력 사건들에 의해 응용프로그램이 죽게 될 것이다. 그런 일이 생기면 Monkey 도구는 무작위 입력을 중단하고 오류를 보고한다. 이런 기능은 품질 보증 작업에 아주 유용하다.
응용프로그램에 대해 Monkey 실행
monkey의 명령 구문은 다음과 같다. adb shell monkey -p <package> <options> <event count> 다음은 에뮬레이터에 있는 GroceryList 응용프로그램에 다섯 개의 무작위 사건을 보내는 예이다. adb -s emulator-5554 shell # monkey -p com.androidbook.grocerylist 5
Monkey의 행동보기
-v 옵션을 주면 Monkey가 발생하는 사건들을 볼 수 있다. 예를 들어 Monkey가 GroceryList 응용 프로그램에게 무작위 사건 다섯 개를 보내게 하되 그 사건들이 구체적으로 어떤 것인지를 알고 싶다면 다음과 같이 하면 된다.
사건 종류에 가중치를 부여함으로써 Monkey가 특정 종류의 사건들을 더/덜 발생하게 만들 수 있다. Monkey가 발생하는 사건 종류와 기본 백분율이 표에 정리 되어 있다.
<안드로이드 프로그래밍 부록 C p610 표 C.1 참고>
예) monkey -p com.androidbook.grocerylist --pct-nav 50 --pct-majornav 50 -v 5 ( 기본 내비게이션과 주 내비게이션 사건들이 50 대 50 의 비율로 발생하게 하는 예이다. )
재현 가능한 무작위 사건 발생
무작위 사건 발생을 위해 Monkey 가 사용하는 난수열의 종잣값(seed)을 명시적으로 지정할 수 있다. 이 기능을 이용하면, 무작위한 사건들을 발생하되 필요하다면 나중에 그 사건들을 똑같이 다시 재현 하는 것이 가능하다 ( 이를 테면 버그가 제대로 고쳐졌는지를 확인하는 데 활용할 수 있다.) 종잣값을 지정하는 옵션은 -s이다. monkey -p <패키지> -s <종잣값> -v <사건 개수> 다음은 555라는 종잣값에 비롯된 다섯 무작위 사건들을 GroceryList에 보내는 예이다,. monkey - p com.androidbook.grocerylist -s 555 -v 5 종잣값이 다르면 Monkey가 발생하는 사건들도 달라진다. 반대로, 같은 종잣값을 지정하면 항상 동일한 사건들이 발생한다. 이는, 사건들을 재현하기 위해서는 종잣값을 기억해 둘 필요가 있다는 뜻이다. 한가지 방법은, 미리 무작위한 종잣값들을 만들어 두고, 그 종잣값을 (또한 종류별 발생 비율 등 기타 옵션들도)버그 보고서나 디버그 로그에 기록해 두는 것이다. 이후 버그 교정을 확인할 때 그 종잣값을 다시 지정함으로써 오작동을 일으킨 사건들을 재현 할 수 있다.
사건 발생 속도 제어
기본적으로 Monkey는 사건들을 최대한 빠르게 발생한다. 발생 속도를 변경하고 싶다면 다음과 같이 --throttle 옵션을 사용하면 된다: monkey --throttle <밀리 초 단위 시간> <사건 개수> 다음은 다섯 개의 무작위 사건을 1초(1000밀리초) 간격으로 GroceryList 응용프로그램에 보내는 예이다. monkey -p com.androidbook.grocerylist -v --throttle 1000 5
The Monkey is a program that runs on your emulator or device and generates pseudo-random streams of user events such as clicks, touches, or gestures, as well as a number of system-level events. You can use the Monkey to stress-test applications that you are developing, in a random yet repeatable manner.
Overview
The Monkey is a command-line tool that that you can run on any emulator instance or on a device. It sends a pseudo-random stream of user events into the system, which acts as a stress test on the application software you are developing.
The Monkey includes a number of options, but they break down into four primary categories:
Basic configuration options, such as setting the number of events to attempt.
Operational constraints, such as restricting the test to a single package.
Event types and frequencies.
Debugging options.
When the Monkey runs, it generates events and sends them to the system. It also watches the system under test and looks for three conditions, which it treats specially:
If you have constrained the Monkey to run in one or more specific packages, it watches for attempts to navigate to any other packages, and blocks them.
If your application crashes or receives any sort of unhandled exception, the Monkey will stop and report the error.
If your application generates an application not responding error, the Monkey will stop and report the error.
Depending on the verbosity level you have selected, you will also see reports on the progress of the Monkey and the events being generated.
Basic Use of the Monkey
You can launch the Monkey using a command line on your development machine or from a script. Because the Monkey runs in the emulator/device environment, you must launch it from a shell in that environment. You can do this by prefacing adb shell to each command, or by entering the shell and entering Monkey commands directly.
The basic syntax is:
$ adb shell monkey [options]<event-count>
With no options specified, the Monkey will launch in a quiet (non-verbose) mode, and will send events to any (and all) packages installed on your target. Here is a more typical command line, which will launch your application and send 500 pseudo-random events to it:
$ adb shell monkey -p your.package.name -v 500
Command Options Reference
The table below lists all options you can include on the Monkey command line.
Category
Option
Description
General
--help
Prints a simple usage guide.
-v
Each -v on the command line will increment the verbosity level. Level 0 (the default) provides little information beyond startup notification, test completion, and final results. Level 1 provides more details about the test as it runs, such as individual events being sent to your activities. Level 2 provides more detailed setup information such as activities selected or not selected for testing.
Events
-s <seed>
Seed value for pseudo-random number generator. If you re-run the Monkey with the same seed value, it will generate the same sequence of events.
--throttle <milliseconds>
Inserts a fixed delay between events. You can use this option to slow down the Monkey. If not specified, there is no delay and the events are generated as rapidly as possible.
--pct-touch <percent>
Adjust percentage of touch events. (Touch events are a down-up event in a single place on the screen.)
--pct-motion <percent>
Adjust percentage of motion events. (Motion events consist of a down event somewhere on the screen, a series of pseudo-random movements, and an up event.)
--pct-trackball <percent>
Adjust percentage of trackball events. (Trackball events consist of one or more random movements, sometimes followed by a click.)
--pct-nav <percent>
Adjust percentage of "basic" navigation events. (Navigation events consist of up/down/left/right, as input from a directional input device.)
--pct-majornav <percent>
Adjust percentage of "major" navigation events. (These are navigation events that will typically cause actions within your UI, such as the center button in a 5-way pad, the back key, or the menu key.)
--pct-syskeys <percent>
Adjust percentage of "system" key events. (These are keys that are generally reserved for use by the system, such as Home, Back, Start Call, End Call, or Volume controls.)
--pct-appswitch <percent>
Adjust percentage of activity launches. At random intervals, the Monkey will issue a startActivity() call, as a way of maximizing coverage of all activities within your package.
--pct-anyevent <percent>
Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses, other less-used buttons on the device, and so forth.
Constraints
-p <allowed-package-name>
If you specify one or more packages this way, the Monkey will only allow the system to visit activities within those packages. If your application requires access to activities in other packages (e.g. to select a contact) you'll need to specify those packages as well. If you don't specify any packages, the Monkey will allow the system to launch activities in all packages. To specify multiple packages, use the -p option multiple times ? one -p option per package.
-c <main-category>
If you specify one or more categories this way, the Monkey will only allow the system to visit activities that are listed with one of the specified categories. If you don't specify any categories, the Monkey will select activities listed with the category Intent.CATEGORY_LAUNCHER or Intent.CATEGORY_MONKEY. To specify multiple categories, use the -c option multiple times ? one -c option per category.
Debugging
--dbg-no-events
When specified, the Monkey will perform the initial launch into a test activity, but will not generate any further events. For best results, combine with -v, one or more package constraints, and a non-zero throttle to keep the Monkey running for 30 seconds or more. This provides an environment in which you can monitor package transitions invoked by your application.
--hprof
If set, this option will generate profiling reports immediately before and after the Monkey event sequence. This will generate large (~5Mb) files in data/misc, so use with care. See Traceview for more information on trace files.
--ignore-crashes
Normally, the Monkey will stop when the application crashes or experiences any type of unhandled exception. If you specify this option, the Monkey will continue to send events to the system, until the count is completed.
--ignore-timeouts
Normally, the Monkey will stop when the application experiences any type of timeout error such as a "Application Not Responding" dialog. If you specify this option, the Monkey will continue to send events to the system, until the count is completed.
--ignore-security-exceptions
Normally, the Monkey will stop when the application experiences any type of permissions error, for example if it attempts to launch an activity that requires certain permissions. If you specify this option, the Monkey will continue to send events to the system, until the count is completed.
--kill-process-after-error
Normally, when the Monkey stops due to an error, the application that failed will be left running. When this option is set, it will signal the system to stop the process in which the error occurred. Note, under a normal (successful) completion, the launched process(es) are not stopped, and the device is simply left in the last state after the final event.
--monitor-native-crashes
Watches for and reports crashes occurring in the Android system native code. If --kill-process-after-error is set, the system will stop.
--wait-dbg
Stops the Monkey from executing until a debugger is attached to it.
- ADB 사용법 추가 확인 주소 : http://developer.android.com/guide/developing/tools/adb.html#commandsummary
@ 안드로이드 파일시스템과 데이터 구조
: 물리 메모리와 파일시스템과 데이터 구조는 안드로이드 기기의 데이터 저장소를 위한 기본요소다. 그러한 요소들을 깊이 있게 이해하게 되면 안드로이드 기기를 잘 이해할 수 있을 뿐만 아니라 새롱누 파일시스템과 데이터 구조를 보게 되더라도 스스로 조사할수 있게 된다.
- yaffs2.tar.gz 를 다운 받아서 설치한 뒤 디바이스에 마운트해서 해당 값을 확인할 수 있다.
- Shared Preferences
-- boolean, float, int, long, strings 에 대한 값이 저장된다.
-- 경로 : /data/data/apk_pkg_name/shared_prefs
- SQLite 정보 위치 ( /data/data/com.android.webkit )
-- app_icons, app_cache, app_geolocation : 아이콘 DB 1개 , 웹 어플 데이터 캐시 1개, GPS 위치와 권한과 관련된 DB 2개
-- app_databases 웹사이트 지원을 위한 로컬 데이터 베이스 저장소를 제공하는 21개의 데이터 베이스
-- databases : 브라우저와 브라우저 캐시를 위한 데이터 베이스 3개
- db 보는 명령어
-- sqlite3 db.db
@ 안드로이드 포렌식 기술
: 안드로이드 기기에서 포렌식 이미지를 획득하기 위한 기술을 여러가지가 있다. 만약 분석 대상 기기가 패스코드로 보호돼 있다면 그것을 회피하거나 우회해서 데이터를 추출해야만 한다. 패스코드를 회피하기 위한 기술을 여러가지가 있지만 어느 상황에서나 항상 패스코드를 회피하는 것은 불가능하다. 일단 기기에 접근 가능하면 포렌식 분석가는 삭제되지 않은 데이터에 초점이 맞춰진 콘텐트 프로바이더를 통한 논리적인 데이터 획득이나 물리적인 데이터 획득 방법 중에서 어느 기술을 사요할 것인지 선택할 수 있다. 물리적 데이터 획득 기술은 이용하면 더 많은 데이터를 얻을 수 있지만 일반적으로 더 복잡한 분석 기술을 필요로 한다.
- APK 보안 검토 툴 : http://viaforensics.com/appwatchdog/
- AFLogical : 콘텐트 프로바이더로 접근할 수 있는 정보를 추출한다. viaForensics에서 무료 배포.
: 조사할 안드로이드 기기를 획득하는 것은 연구나 개발, 논의 에 있어서 매우 주요한 부분이지만 안드로이드 포렌식에서는 단지 시작일 뿐이다. 분석을 위해서는 논리적 물리적 기술이 모두 필요하다. 하지만, 물리적 데이터 획득 이후에 더 많은 양의 분석이 요구 된다. 이 부분에서 목적은 포렌식 분석가나 보안 엔지니어가 안드로이드 기기를 조사할 수 있는 기술, 심지어 포렌식 툴이 제대로 지원하지 못하는 파일시스템이라고 하더라도 그것을 조사할 수 있는 기술을 제공하는 것이다. 기존의 포렌식 툴과 리눅스 명령. 그리고 경우에 따라서는 헥스 분석을 사용하면 조사가 필요한 데이터 대부분을 분석할 수 있다.
- Hex : 포렌식 분석가의 좋은 친구
-- $ sudo apt-get install ncurses-hexedit // 매우 빠른 터미널 기반의 헥스 에디터; 다른 것을 써도 된다.
- strings 를 활용해서 정보의 갯수를 알 수 있다; 정보의 유/무
-- $ strings --all --radix=x mmssms.db | grep 312123123 | wc -l // 해당 정보 312123123가 몇 개 존재하는 지 알수 있다.
- FAT 포렌식 분석
-- log2timeline을 이용한다. 그 전에 앞에서 활용했던 SD 카드 이미지 만들기, TSK의 mmls로 이미지를 조사하고, 이미지를 마운트해야 한다. ( 기타 추가 설명은 p 384에 있다. )
하지만 이런 경우 Decor되기 위한 View로 변환(.getDecorView())되어 버린 액티비티들은, 원래 액티비티가 가지고 있는 라이프 사이클을 완전하게 수행하지 못하게 되어버렸습니다.
그래서 Intent 플래그 중 FLAG_ACTIVITY_CLEAR_TOP 을 써서 계속해서 새로 호출하며 화면을 갱신하는 방법을 택하지 않았었나 생각되구요. (기본적으로 생성:onCreate()onDestroy()과 파괴:onDestroy()는 수행이 됨) ActivityGroup이라는 공통의 부모가 있기는 하지만, 자식 액티비티들간의 데이터의 교환도 어려웠구요.
어쨋든 이런 문제점들과, 태블릿의 특성인 한 화면 안에서 여러개의 액티비티를 동시에 보여주는것에 적합하게 나온것이 Fragment입니다.
액티비티 대신에 Fragment라는 녀석으로 조각 조각 따로 만들어 주는 거지요.
예전 방식이 리스트를 보여주는 액티비티 A에서 뭔가를 눌렀을 때, 그 내부 컨텐츠를 보여주는 액티비티 B로 이동하는 형식이었다면, Fragment는 한번에 리스트와 컨텐츠를 동시에 한 화면에서 볼 수 있게 해 주는 것입니다. 이때 왼쪽의 리스트 부분을 하나의 fragment로, 오른쪽의 컨텐츠 부분을 다른 하나의 fragment로 구성을 해주고, 이 둘을 가지고 있는 Activity가 존재하는 것이지요.
ActivityGroup에서의 Child Activity와 비교하여
생각해보면, ActivityGroup과 개념이 많이 다르지 않습니다. ActivityGroup은 Child Activity들을 View로 만들어서 화면에 보여주는 것이라면, Honeycomb에서는 View대신에 Fragment라는 것을 사용해서 Activity와 유사한 방식의 Lifecycle을 갖는 조금 다른 뷰를 만들어내서 화면에 보여주는게 된것이죠.
Activity 기반의 Lifecycle을 가지고 있기 때문에, 실제 액티비티 하나를 운용하는것 처럼 사용하면 됩니다.
Fragment는 일반 객체처럼 new 키워드를 사용해서 생성하게 됩니다. 기존에 액티비티에서 사용하는 startActivity와는 조금 다르죠.
또 한화면에 여러개의 Fragment를 동시에 보여줄 수 있기때문에, 한번에 보여지는 Fragment들간에 데이터 교환이 빈번하게 발생하게 되는데, Activity에서 하듯이 intent를 통해서 하는게 아닌, interface를 통해서 데이터를 교환하면 되기 때문에 상당히 편리해진것을 느낄 수 있습니다.
Fragment의 생성, Activity에 붙이기(Attach)
기본적인 Honeycomb, 태블릿 UI를 구성을 생각하면, 좌측에 리스트가 보이고, 우측에 리스트에서 선택한 컨텐츠가 보이는 형식일겁니다.
간단한 예제를 만들기 위해, 아래와 같이 세개의 클래스를 만들어줍니다.
ExampleFragmentActivity extends Activity ExampleListFragment extends Fragment ExampleContentFragment extends Fragment
// FragmentTransaction을 통해 Fragment에 대한 변경사항을 적용한다.
ft.commit();
}
생성은 일반적인 자바 객체를 생성하듯 new 를 사용해서 생성해줍니다.
// 왼쪽의 List로 사용할 ExampleListFragment를 생성한다. ExampleListFragment listFragment = newExampleListFragment();
액티비티에 붙이는 건, FragmentTransaction의 replace메소드를 이용합니다. // FragmentTransaction의 replace메소드를 통해, 액티비티에 붙인다. ft.replace(R.id.example_fragment_activity_ll_list_fragment, listFragment, TAG_LIST);
Activity로부터 Fragment 가져오기
Activity의 어느 메소드라도, Fragment를 액티비티에 붙인 이후에는, 아래와 같은 코드를 통해 Activity에 붙어있는 Fragment를 가져올 수 있습니다. 이때 String tag를 사용해서 가져올 수 있습니다. 태그는 위에서 액티비티에 프래그먼트를 붙일 때 사용했던 태그입니다.
- Fragment 는 Activity에 포함 가능한 sub activity로 볼 수 있는데, Activity 의 life cycle 과 비슷한 cycle 을 타고 간다. Fragment 도 Activity 처럼 extends 를 해서 작성 및 사용한다.
- Fragment 는 Xml 에서도 정의 가능한데 <fragment> 태그를 사용한다.
- Fragment 는 Back Stack 을 가지고 있다. 이것은 system 에서 관리해주는 activity back stack 과는 다르며, activity 에 유지되는, programmer 가 관리하는 back stack 이다.
- Fragment 의 life cycle 중 onCreate(), onCreateView(), onPause() 는 거의 반드시 기술한다. onCreate 는 생성시, onCreateView 는 View 최초 생성시 호출되며, onCreateView는 fragment의 root view 를 return 한다. onPause 는 activity life cycle 의 onPause 와 비슷하다.
- Fragment 의 sub class 들은 DialogFragment, ListFragment, PreferenceFragment 들이 있다.
- system 이 fragment 를 restore 할 때 ( 예를 들면 activity 의 restart ), fragment 들을 구분하기 위해서 fragment 에 id 를 부여해야 한다. 3가지 방법이 있는데, android:id 로 unique ID 를 주던가, android:tag 로 unique String 을 주면 된다. 둘 다 주지 않으면, system 이 container view 의 ID 를 사용한다.
- fragment 를 add, remove, replace 할 때는 "반드시" FragmentTransaction API 를 사용해야만한다. 다음과 같은 방법으로 해준다.
fragmentTransaction.add(R.id.fragment_container, fragment); // first param is viewgroup id.
fragmentTransaction.commit();
- fragment 를 UI 가 없는 녀석으로 만들어 background 작업을 하도록 사용할 수도 있다. 이때는 add( Fragment fragment, String tag ) 를 통해 등록을 한다. 이렇게 등록을 하면 onCreateView() 가 호출되지 않는다. 물론 구현할 필요도 없다. 등록시의 tag 는 findFragmentByTag() 를 통해 해당 fragment 에 접근하는데 쓰인다.
- FragmentManager 를 통해서 fragment 를 control 하는데 다음과 같은 일들을 할 수 있다.
1. findFragmentById 나 findFragmentByTag 를 통해서 fragment 를 얻어올 수 있다.
2. popBackStack() 을 통해 Activity 에서 BackKey 를 누른 것과 비슷한 효과를 낼 수 있다.
3. addOnBackStackChangedListener 를 통해 listener 등록도 가능하다.
4. FragmentTransaction 을 얻어 operation 을 할수도 있다.
- FragmentTransaction 을 통해, add(), remove(), replace(), commit() 등을 호출 가능하고, addToBackStack() 을 통해 activity 에서 관리하는 back stack 에 FragmentTransaction 을 등록 가능하다. BackKey 가 눌렸을 때 back stack 이 작동한다.
- fragment 가 addTobackStack() 을 통해 remove 되는 경우는 stopped state 에 들어가고, 그렇지 않을 경우에는 destory state 로 들어간다.
- commit() 전에 setTransition() API 를 통해, transition animation 을 줄 수 있다.
- commit() 된 transaction 은 바로 실행되지 않고, main thread 에 schedule 되어 처리된다.executePendingTransaction() 을 통해 commit() 된 녀석을 바로 실행시킬 수 있지만, 다른 thread 와의 work 에 dependency 가 있지 않는 한은 쓸 일이 없을 것이다.
- commit() 은 activity 가 state save 하기 전에 이루어져야 한다. state save 후에 commit() 이 불린다면 exception 이 발생한다. 만약 state save 와 관계없이, fragement 의 state 저장과 관련없게 작동하게 하려면 commit() 대신 commitAllowingStateLoss() 를 호출해줘야 한다.
- Fragment 에서 option menu를 구성하려면 onCreate() 에서 setHasOptionsMenu() 를 call 해주어야 한다. 그렇지 않으면, fragment의 onCreateOptionsMenu() 가 불리지 않는다. 마찬가지로, menu item 이 click 되면 onOptionsItemSelected() 가 호출된다.
- fragment 에도 registerForContextMenu() API 가 있으며, context menu 생성시 onCreateContextMenu() 가 불리고, item click 시 onContextItemSelected() 가 불린다.
- Fragment 에 전달되는 event 들은 사실 activity 가 먼저 받고, 그 다음에 fragment 에 전달이 되는 형태이다. 물론 activity 에서 다 처리하고, fragment 로 전달하지 않도록 하는 방법도 있다.
- fragment 도 bundle 에 state 를 저장할 수 있다. fragment 의 onSaveInstanceState() 에서 저장하고, onCreate(), onCreateView() 혹은 onActivityCreated() 에서 restore 해주면 된다.